java中的holder类,SpringContextHolder工具类

1.工具类用途?

该工具类主要用于那些没有归入spring框架管理的类却要调用spring容器中的bean提供的工具类,在spring中要通过IOC依赖注入来取得对应的对象,但是该类通过实现ApplicationContextAware接口,以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.如此就不能说说org.springframework.context.ApplicationContextAware这个接口了

2.ApplicationContextAware接口作用?

当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。除了以上SpringContextHolder类之外,还有不需要多次加载spring配置文件就可以取得bean的类。

3.setApplicationContextAware( )何时执行?

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 getBean(String beanName) {

assertApplicationContext();

return (T) applicationContext.getBean(beanName);

}

public static T getBean(Class requiredType) {

assertApplicationContext();

return applicationContext.getBean(requiredType);

}

private static void assertApplicationContext() {

if (SpringContextHolder.applicationContext == null) {

throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");

}

}

}

修改配置文件spring-context.xml,添加bean:

项目中的使用,例如UserRoleService.java:

private  UserService userService= SpringContextHolder.getBean(UserService.class);

注意:

1.如果启动项目后报错 "applicaitonContext属性为null,请检查是否注入了SpringContextHolder!",因为SpringContextHolder中的applicationContext为空,猜测是SpringContextHolder这个bean没有在UserRole这个bean加载前进行加载,导致没有加载完成,所以我们需要在配置文件中首先加载SpringContextHolder。把放在配置文件的第一个加载位置,再启动项目发现正常。

2.在使用该类静态方法时必须保证spring加载顺序正确, 也可以通过在使用类上添加 @DependsOn(“springContextHolder”),确保在此之前 SpringContextHolder 类已加载!