通過ApplicationContextAware接口來保存Spring ApplicationContext

測試代碼

package com.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextHolder implements ApplicationContextAware{

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.context = applicationContext;
        System.out.println((applicationContext==null) + "-----------");
    }

    /**
     * 取得存儲在靜態變量中的ApplicationContext.
     */
    public ApplicationContext getApplicationContext(){
        return context;
    }

    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }
}

1.實現ApplicationAware接口中的方法,通過注入來設置ApplicationContext

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <display-name>test</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

1.讀取classpath下面的application.xml配置文件

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <description>Spring Configuration</description>

    <bean id="springContextHolder" class="com.common.utils.SpringContextHolder"/>
</beans>

1.啓動Tomcat,輸出false———–,成功注入
2.這樣就可以在任何地方取出ApplicationContext來使用
3.通過調用SpringContextHolder.getBean方法來取出對象使用
4.這裏注意application.xml放的位置,我放在test/resource目錄下,test是project名,也就是classpath下面,在web.xml中有指定讀取位置

當然也可以不用寫bean直接在application.xml中使用標籤context:component-scan進行掃描,並在SpringContextHolder的類名上面標註上@Service

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章