spring ApplicationContextAware的那些事儿

在基于spring框架的B/S应用中,有时候需要在其他比如其他servlet等不属于spring容器范围中获取bean时,可用ApplicationContextAware来帮助我们。
废话不多说,直接上例子:

第一步,需要编写类实现ApplicationContextAware接口,如下面的AppUtil 类:

@Component
public class AppUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public AppUtil(){
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public static void setContext(ApplicationContext applicationContext){
        AppUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String paramString) {
        return applicationContext.getBean(paramString);
    }
}

第二步,实现一个特定的servlet,如

public class ApplicationContextLoaderServlet extends HttpServlet {  

private static final long serialVersionUID = 1L;

public void init(ServletConfig config) throws ServletException {
    AppUtil.setContext(
            WebApplicationContextUtils.getWebApplicationContext(
                config.getServletContext()));
    }
}

第三步,将该servlet配置到web.xml

<servlet>
    <servlet-name>ApplicationContextLoaderServlet</servlet-name>
    <servlet-class>
        com.easyfee.core.web.servlet.ApplicationContextLoaderServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

然后,童鞋们就可以再需要获得bean的地方进行使用了,如:
MyService myService = (MyService ) AppUtil
.getBean(“myService”);

希望这篇文章对大家有所帮助。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值