ApplicationContextAware get bean

ApplicationContextAware

Outline

  • In some special cases, Bean need to achieve a certain function, but this function must be achieved by means of the Spring container, then you must make the first acquisition Bean Spring container, and then by means of the Spring container to achieve this function. In order to obtain it in the Spring Bean container, allowing the Bean implementation ApplicationContextAware interface.
  • All Bean Spring container will detect the container, if you find a Bean implements ApplicationContextAware interfaces, Spring containers will be created after the Bean, the Bean is automatically invoked setApplicationContextAware () method, the method is called, will the container itself as an argument passed to the method - the method to achieve some of the parameters passed Spring (container itself) is assigned to the object class instance variables applicationContext, so we can now be accessed by the vessel itself applicationContext instance variable.

    use

public class SpringContextHolder implements ApplicationContextAware {  
    private static ApplicationContext applicationContext = null;  
  
    /** 
     * 获取静态变量中的ApplicationContext. 
     */  
    public static ApplicationContext getApplicationContext() {  
        assertContextInjected();  
        return applicationContext;  
    }  
  
    /** 
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
     */  
    @SuppressWarnings("unchecked")  
    public static <T> T getBean(String name) {  
        assertContextInjected();  
        return (T) applicationContext.getBean(name);  
    }  
  
    /** 
     * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. 
     */  
    public static <T> T getBean(Class<T> requiredType) {  
        assertContextInjected();  
        return applicationContext.getBean(requiredType);  
    }  
  
    /** 
     * 清除SpringContextHolder中的ApplicationContext为Null. 
     */  
    public static void clearHolder() {  
        applicationContext = null;  
    }  
  
    /** 
     * 实现ApplicationContextAware接口, 注入Context到静态变量中. 
     */  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextHolder.applicationContext = applicationContext;  
    }  
  
    /** 
     * 检查ApplicationContext不为空. 
     */  
    private static void assertContextInjected() {  
        Validate.validState(applicationContext != null,  
                "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");  
    }  
  
} 

Guess you like

Origin www.cnblogs.com/frankltf/p/11369229.html