Spring is even more powerful, and it also needs to face the problem-Because Spring is not a top-layer container like Weblogic and Tomcat, Servlet and EJB objects cannot be created by it, therefore, it must come to the location of Weblogic and Tomcat.
Beginners generally don't need to worry so much about it. Just follow the Sample such as Spring + hibernate + Struts, but slowly, it may be necessary to begin in the jsp + javabean system, the local framework, spring is used in singleton and other environments.
Chapter 3rd of Professional Java Development with the Spring Framework describes this issue in the section "Managing the Containe. Generally, it can be divided into direct calling and IoC fashion.
1. Direct call-Singleton's Application Context
The simplest way is to directly construct the Application Context as in UnitTest:
ApplicationContext ctx = new ClasspathXmlApplicationContext ("ApplicationContext. xml ");
In the Web environment, ContextLoader is used to construct ApplicationContext and press it into Servlet Context.
ContextLoaderListener or ContextLoaderServlet, which is completed when the Web application is started.
Then, in Jsp/Servelet, you can use Servlet Context to obtain ApplicationContext: ApplicationContext context = WebApplicationContextUtils. getWebApplicationContext (application );
However, no Servlet Context is available in the singleton class or EJB.
If they are all constructed as directly as UnitTest, the speed will be very bad. Naturally, we thought of making ApplicationContext into a singleton.
Spring provides objects such as ContextSingletonBeanFactoryLocator.
Create a beanreffacloud. xml file with all the applcationContext-*. xml file names in it, and name the Context "default-context": <beans>
<Bean id = "default-context" class = "org. springframework. context. support. ClassPathXmlApplicationContext">
<Constructor-arg>
<List> <value> applicationContext. xml Value> List>
Constructor-arg>
Bean>
Beans>
Then let loactor find it, but the code is a bit long: BeanFactoryReference bfr = DefaultLocatorFactory. getInstance (). useBeanFactory ("default-context ");
BeanFactory factory = bfr. getFactory ();
MyService myService = factory. getBean ("myService ");
Bfr. release ();
// Now use myService
The above code is too flexible and too troublesome.
It is better to implement a simple Singleton, expand the ContextLoaderListener class, and press Singleton when the Web system starts.
The new ContextLoaderListener class overload is as follows. ContextUtil contains a static ApplicationContext variable:
Public void contextInitialized (ServletContextEvent event)
{
Super. contextInitialized (event );
ServletContext context