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> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

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

xml配置

web.xml

<servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:SpringServlet.xml</param-value>
        </init-param>
        <!--随tomcat启动一起加载 -->
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

SpringServlet.xml

<!-- 可通过SpringContextUtil获取Spring容器中的任何bean -->
    <bean id="springContextUtil" class="com.kylin.aep.utils.SpringContextUtil"
        scope="singleton" />

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

使用

 PermeateService permeateServiceImpl = SpringContextUtil.getBean(PermeateServiceImpl.class);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值