当前页面: 开发资料首页 → JSP 专题 → 在厨房,车顶,草地上使用Spring
摘要: 在厨房,车顶,草地上使用Spring
Spring再强大,也要面对降临的问题--因为Spring不是Weblogic、Tomcat般的顶层容器,Servlet和EJB对象不由它创建,所以它必须要降临到Weblogic、Tomcat所在的位面。
初学者一般不用管那么多,照着Spring+hibernate+Struts之类的Sample就做了,但慢慢的,也许就要开始在jsp+javabean体系,土制框架,Singleton类等环境下使用Spring了。
《Professional Java Development with the Spring Framework》第3章有"Managing the Containe"一节讲这个问题。一般可以分为直接召唤系与IoC fashion两类。
1.直接召唤系--Singleton的Application Context
最简单的,就像在UnitTest里那样,直接构造Application Context:
ApplicationContext ctx = new ClasspathXmlApplicationContext("ApplicationContext.xml");
<beans>
<bean id="default-context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list> <value>applicationContext.xml</value></list>
</constructor-arg>
</bean>
</beans>
BeanFactoryReference bfr = DefaultLocatorFactory.getInstance().useBeanFactory("default-context");
BeanFactory factory = bfr.getFactory();
MyService myService = factory.getBean("myService");
bfr.release();
// now use myService
public void contextInitialized(ServletContextEvent event)
{
super.contextInitialized(event);
ServletContext context = event.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
ContextUtil.setContext(ctx);
}
ApplicationContext context = ContextUtil.getContext();