Spring中ApplicationContextAware接口的用法

1.为什么使用AppplicationContextAware?

      ApplicationContext的BeanFactory 的子类, 拥有更强大的功能,ApplicationContext可以在服务器启动的时候自动实例化所有的bean,而 BeanFactory只有在调用getBean()的时候才去实例化那个bean, 这也是我们为什么要得到一个ApplicationContext对象, 事实上Spring2相关的web应用默认使用的是ApplicationContext对象去实例化bean, 换一句话说, 在服务器启动的时候,Spring容器就已经实例化好了一个ApplicationContext对象,所以我们要在老的代码里尝试去获取这个对象。 但是如何才能得到一个ApplicationContext对象呢?方法很多,最常用的办法就是用ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApplicationContext 等对象去加载Spring配置文件,这样做也是可以, 但是在加载Spring配置文件的时候,就会生成一个新的ApplicaitonContext对象而不是Spring容器帮我们生成的哪一个, 这样就产生了冗余, 所以我们在这里不采用这种加载文件的方式,我们使用ApplicationContextAware让Spring容器传递自己生成的ApplicationContext给我们, 然后我们把这个ApplicationContext设置成一个类的静态变量, 这样我们就随时都可以在老的代码里得到Application的对象了。(转载自   https://blog.csdn.net/kouwoo/article/details/43405109)

2. ApplicationContextAware接口作用 ?

       加载Spring配置文件时,如果Spring配置文件中所定义或者注解自动注入的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的方法:

           public void setApplicationContext (ApplicationContext context) throws BeansException

3.如何实现的

     首先创建工具类实现ApplicationContextAware 

      

public class GetBeanInstance implements ApplicationContextAware {

    
    private static final Logger logger = LoggerFactory.getLogger(GetBeanInstance.class);

    private static ApplicationContext applicationContext = null;

    /***
     * 当继承了ApplicationContextAware类之后,那么程序在调用 getBean(String)的时候会自动调用该方法,不用自己操作
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.info("setApplicationContext :::: " + applicationContext);
        GetBeanInstance.applicationContext = applicationContext;
    }
     // 获取 bean
    public static Object getBean(String beanName) {
        try {
            if(applicationContext == null){
                logger.error("applicationContext is null");
            }
            return applicationContext.getBean(beanName);
        } catch (Exception e) {
            logger.warn("not fund bean [" + beanName + "]", e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return (T) getBean(beanName);
    }

    public static Object getBeanThrowException(String beanID) {
        return getBeanThrowException(beanID, Object.class);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBeanThrowException(String beanID, Class<T> clazz) {

        if (beanID == null || "".equals(beanID)) {
            throw new IllegalArgumentException("beanID is empty [" + beanID + "]");
        }

        try {
            return (T) applicationContext.getBean(beanID);
        } catch (Exception e) {
            logger.error("not fund bean [" + beanID + "]", e);
            throw new NullPointerException("not fund bean [" + beanID + "] !!!!!!!");
        }
    }


}

   然后配置 GetBeanInstance

 <bean id="GetBeanInstancesAPI" class="com.sinosoft.utility.GetBeanInstance" scope="singleton" lazy-init="false"  />

  最后配置web.xml  

        因为spring要建立属于自己的容器,就必须要加载自己的配置文件。     这个时候,需要注册ContextLoaderListener或者这个类的子类。

<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>   

       当然,这样子的话只会读取默认路径下的application.xml配置文件的。如果需要读取特定路径下的配置文件。需要在web.xml中添加如下信息。

	<context-param>
		<param-name>contextConfigLocation</param-name>      //这行不允许改动
		<param-value>
			classpath:applicationContext.xml
		</param-value>
	</context-param>

  到这就就大功告成了。虽然还是迷迷糊糊,但总算是了解了一些知识。

原文地址:https://www.cnblogs.com/muqingzhi123/p/9805623.html