Getting Spring Application context from a non bean object

本文介绍了一种通过自定义上下文管理器(AppContextManager)在非Spring环境中获取Spring Bean实例的方法。该方法首先创建一个实现了ApplicationContextAware接口的组件,然后通过静态方法提供对ApplicationContext的访问,从而可以在项目的任何地方获取所需的Spring Bean。

First create a class called AppContextManager like below:

@Component
public class AppContextManager implements ApplicationContextAware{
    private static ApplicationContext _appCtx;

    @Override
    public void setApplicationContext(ApplicationContext ctx){
         _appCtx = ctx;
    }

    public static ApplicationContext getAppContext(){
        return _appCtx;
    } 
}

Annotate the above class with @Component or declare a bean for AppContextManager in your application context xml.

Now in your non-singleton non-spring instance use the following code snippet to obtain any other spring bean:

ApplicationContext ctx = ApplicationContextManager.getAppContext();
SomeSpringBean bean = ctx.getBean(SomeSpringBean.class);

And this would give you the bean instance anywhere in your code.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值