Various methods of obtaining applicationcontext in spring

Source: Internet
Author: User

Original source: Xieyu_zy

Why do you write this article? Spring different versions, and the framework of the system is different, resulting in different ways to obtain, the network of various versions, too chaotic, write access to the way the people do not write this access is in the local or the Web, under the kind of application server, in the spring version, too much!

I write some, common, and probably often used versions;

first of all, why get this thing : When you want to get an instance of a class that you specify through spring, and you don't load it into the currently called Class by spring, for example, you might want to judge a person's role in the filter, There is no business layer code at this time, but you have to access the database or other service classes.

and then make sure : This context is a global variable, and when spring loads, the root handle information is loaded, whether it's a local application or a Web application, and the following are some of the ways to get local programs and other situations.

If the main method, you want to start spring, there are many methods, there are annotation-based annotations in terms of the configuration file loading, of course, you want to get applicationcntext can be obtained in the Main method:

1 XmlBeanFactory factory = newXmlBeanFactory(newClassPathResource("beans.xml"));//这样来加载配置文件

Is there any other way? Some

1 ApplicationContext context = newClassPathXmlApplicationContext(newString[] {"a.xml", "b.xml"});

Is there anything else? Yes

123456 < Code class= "Java plain" >xmlwebapplicationcontext context = new xmlwebapplicationcontext (); context.setconfiglocations ( new string[" { "Bb.xml" }); mockservletcontext msc = new mockservletcontext (); context.setservletcontext (MSC); context.refresh (); msc.setattribute (Webapplicationcontext.root_web_application_context_attribute, CONTEXT );

Actually the method is similar, they have the inheritance relation, therefore the method is many, each time you new, is equivalent to re-create a applicationcontext, he will reload, so is not suitable repeatedly calls, if oneself new, You should put it in a global variable, start with main, and of course you can apply it directly or indirectly to the application .

On the web, there is one way to load spring itself through spring:

By implementing an interface:

1 org.springframework.context.ApplicationContextAware

Then spring reflects, source article: Http://blog.163.com/[email protected]/blog/static/2684016320101028101923914/

This method is valid in spring 2 and 3:

To write a class:

123456789101112131415161718192021222324 import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Service;@Servicepublic class SpringContextHolder implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        SpringContextHolder.applicationContext = applicationContext;    }     public static ApplicationContext getApplicationContext() {        return applicationContext;    }    public static Object getBean(String beanName) {        return applicationContext.getBean(beanName);    }    public static <T>T getBean(String beanName , Class<T>clazz) {        return applicationContext.getBean(beanName , clazz);    }}

I am here to annotate through annotation, if not annotation, then you can pass the configuration file:

1 <beanclass="xxx.xxx.xxx.SpringContextHolder"></bean>

For injection operations, as a result, if the spring configuration is not set byname , the bean configuration will remember to add parameters to set the ApplicationContext to reflect in.

And you have to load spring, many times, not into the business layer, because reflection is reflected to the business layer, you have not entered the business layer, how to get this reflection of things? Unless you use static variables to retrieve them when you reflect them, there is no problem; So the above example uses static as well;

When you do not want to use static to reflect, and often want to use it, there are many ways to obtain.

In the previous versions of Spring 3 , we typically obtained this in Web applications:

1 WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);

And what is CONTEXNT? If it is a servlet, it can be obtained directly from Getservletcontext (),

and through the request to get this:

For all tomcat generic, the notation is:

1 ServletContext context = req.getSession().getServletContext();

For Tomcat 7 above the notation is (that is, Tomcat 7 can get servletcontext,tomcat6 directly from the request, you must pass the session):

1 ServletContext context = req.getServletContext();

In fact, since spring 3, the method has changed and become very strange, because it is not compatible with the previous method of acquisition, Spring 3 in the further packaging, you may see in other places a variety of versions.

The reason that spring 2 can be obtained is because Spring 2 typically configures a listener that he will load spring, before the filter, and Spring 3, through Org.springframework.web.servlet.DispatcherServlet to load spring's information, Initialize in its Father class: Org.springframework.web.servlet.FrameworkServlet method:initwebapplicationcontext ();

The tracking method obviously sees that the internal fetch adds a parameter:

1 WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext(),attrName);

What is this parameter?

Traces can be found to be:

1 FrameworkServlet.SERVLET_CONTEXT_PREFIX + getServletName()

And the definition of Servlet_context_prefix is:

1 publicstatic finalString SERVLET_CONTEXT_PREFIX = FrameworkServlet.class.getName() + ".CONTEXT.";

That is

1 “org.springframework.web.servlet.FrameworkServlet.CONTEXT.”

and Getservletname ()? He is the servlet of the current request, and can get the name of a configuration within the Web. XML, for example,

If your Web. XML is configured with:

12345 <servlet>        <servlet-name>spring</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>

Note that the result of Getservletname () is spring, otherwise, if it is spring, it is:

1 org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring

OK, if you follow the above configuration, the access method is:

1 request.getSession().getServletContext().getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring");

Tomcat 7 or more can be written as:

1 request.getServletContext().getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.spring");

A better formulation is:

1 request.getSession().getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX +"spring");

The following are some of the extensions that spring makes for convenience:

Spring is convenient for obtaining this parameter in the business code, and before entering the business code, an operation is made before the Dispatcherservlet method: Doservice Dodispatch called:

1 request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());

That is, when you enter the controller, the acquisition will not be so troublesome, you just need to obtain:

1 request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);

Of course, you can write the values in and see the definition:

1 publicstatic finalString WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";

Then the value should be:

1 org.springframework.web.servlet.DispatcherServlet.CONTEXT

So in the controller you can also get:

1 request.getAttribute("org.springframework.web.servlet.DispatcherServlet.CONTEXT")

After spring packaging, you can also pass:

1 RequestContextUtils.getWebApplicationContext(request , context)

To obtain, the source code is as follows:

In fact, the way it gets is the same as the method given above,Requestcontextutils.getwebapplicationcontext in spring 3, If you do not start Contextloaderlistener (of course you can configure monitoring), it will not succeed.

The simple configuration of the Contextloaderlistener is (in Web. xml):

123 <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

Spring 3 was not so configured after all.

Ask.-Customized IT education platform, one-to-man service for cattle, questions and answers, development and programming social Headlines official website: www.wenaaa.com

QQ group 290551701 gathers a lot of Internet elite, technical director, architect, project Manager! Open source technology research, Welcome to the industry, Daniel and beginners are interested in engaging in IT industry personnel to enter!

Various methods of obtaining applicationcontext in spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.