SpringContextUtil获取上下文中bean

一.SpringContextUtil类

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext; // Spring应用上下文环境

    /*
     * 实现了ApplicationContextAware 接口,必须实现该方法;
     * 通过传递applicationContext参数初始化成员变量applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static  T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static  T getBean(Class clazz) throws BeansException {
        return (T) applicationContext.getBean(clazz);
    }
}

xml配置

web.xml

<servlet>
        <servlet-name>DispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        servlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath*:SpringServlet.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>

SpringServlet.xml


    <bean id="springContextUtil" class="com.kylin.aep.utils.SpringContextUtil"
        scope="singleton" />

这样,在根据SpringServlet.xml初始化上下文时,会自动调用setApplicationContext()方法去获取ApplicationContext。

使用

 PermeateService permeateServiceImpl = SpringContextUtil.getBean(PermeateServiceImpl.class);

你可能感兴趣的:(java-spring)