环境:与第一、二章相同。依赖于之前创建的工程、库、接口定义、xml或注解配置。
参照RestEasy的两种实现方法:
1.通过WebApplicationContextUtils工具类获取ApplicationContext对象
获取到ApplicationContext就能获取Bean:
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application); UserDao userDao = (UserDao)context.getBean("userDao");
struts2中可通过以下代码获取ServletContext:
ServletContext application = ServletActionContext.getRequest().getSession().getServletContext();
2.自定义工具类
定义Context工具类SpringContextHolder:
package com.sunbin.common.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. * */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; // NOSONAR } /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public staticT getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ public static T getBean(Class clazz) { checkApplicationContext(); return (T) applicationContext.getBean(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException( "applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } } }
root-context.xml增加配置:
工具类中有静态变量applicationContext和非静态set方法,spring加载配置并创建ApplicationContext时,会创建工具类的一个单例bean并将ApplicationContext自身注入bean。之后可以通过工具类的静态方法获取applicationContext并获取Bean。
可通过beanName或beanType获取。
测试类代码:
package com.sunbin.test.testSpring.main; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sunbin.common.spring.SpringContextHolder; import com.sunbin.test.testSpring.service.TestService; public class TestSpringContextHolder { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "root-context.xml" }); TestService testService =(TestService) SpringContextHolder.getBean("testService"); System.out.println(testService.test("helloWorld")); testService =(TestService) SpringContextHolder.getBean(TestService.class); System.out.println(testService.test("helloWorld")); } }
运行结果如下:
- testServiceImpl.test:testDaoImpl.test:helloWorld
- testServiceImpl.test:testDaoImpl.test:helloWorld
说明获取bean成功。