1.工具类用途?java
该工具类主要用于那些没有纳入spring框架管理的类却要调用spring容器中的bean提供的工具类,在spring中要经过IOC依赖注入来取得对应的对象,可是该类经过实现ApplicationContextAware接口,以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任什么时候候中取出ApplicaitonContext.如此就不能说说org.springframework.context.ApplicationContextAware这个接口了spring
2.ApplicationContextAware接口做用?app
当一个类实现了这个接口(ApplicationContextAware)以后,这个类就能够方便得到ApplicationContext中的全部bean。换句话说,就是这个类能够直接获取spring配置文件中,全部有引用到的bean对象。除了以上SpringContextHolder类以外,还有不须要屡次加载spring配置文件就能够取得bean的类。框架
3.setApplicationContextAware( )什么时候执行?ide
Spring容器会检测容器中的全部Bean,若是发现某个Bean实现了ApplicationContextAware接口,Spring容器会在建立该Bean以后,自动调用该Bean的setApplicationContextAware()方法,调用该方法时,会将容器自己做为参数传给该方法——该方法中的实现部分将Spring传入的参数(容器自己)赋给该类对象的applicationContext实例变量,所以接下来能够经过该applicationContext实例变量来访问容器自己。工具
/** * Spring的ApplicationContext的持有者,能够用静态方法的方式获取spring容器中的bean * */ @Component @Lazy(false) public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { assertApplicationContext(); return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } public static <T> T getBean(Class<T> requiredType) { assertApplicationContext(); return applicationContext.getBean(requiredType); } private static void assertApplicationContext() { if (SpringContextHolder.applicationContext == null) { throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!"); } } }
修改配置文件spring-context.xml,添加bean:ui
<bean id="springContextHolder" class="com.utils.SpringContextHolder" lazy-init="false"/>
项目中的使用,例如UserRoleService.java:
private UserService userService= SpringContextHolder.getBean(UserService.class);spa
注意:code
1.若是启动项目后报错 "applicaitonContext属性为null,请检查是否注入了SpringContextHolder!",由于SpringContextHolder中的applicationContext为空,猜想是SpringContextHolder这个bean没有在UserRole这个bean加载前进行加载,致使没有加载完成,因此咱们须要在配置文件中首先加载SpringContextHolder。把<bean id="springContextHolder" class="com.utils.SpringContextHolder" lazy-init="false"/>放在配置文件的第一个加载位置,再启动项目发现正常。
2.在使用该类静态方法时必须保证spring加载顺序正确, 也能够经过在使用类上添加 @DependsOn(“springContextHolder”),确保在此以前 SpringContextHolder 类已加载!
xml