非spring容器管理的模块里使用bean(借助ApplicationContextAware和WebApplicationContextUtils)

本文介绍了在Spring框架中如何在非Spring管理的类中获取Bean。主要通过两种方法实现:利用ApplicationContextAware接口和借助WebApplicationContextUtils工具类。这两种方法都是通过获取Spring上下文ApplicationContext来完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#RT,废话不多说直接进入主题:
        在spring中通常采取注入的方式获取bean,比如

    @Resource
    private SystemConfig systemConfig;

    @Autowired
    private OssService coreConfig;

前提是使用这些注解的类也要纳入spring容器进行管理比如加上注解@Component。

但是,有时候需要在非spring管理的模块里使用bean,比如工具类Untils等。这种情况获取bean的方法有多种,在此只介绍其中之二,

一:借助ApplicationContextAware接口

        编写一个实现ApplicationContextAware接口,这个接口只有一个方法

void setApplicationContext(ApplicationContext var1) throws BeansException;

代码示例:

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

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

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

}

在spring容器加载的时候会执行setApplicationContext方法,拿到ApplicationContext(spring上下文),再通过applicationContext拿到bean,如:

    SystemConfig bean = SpringUtils.getBean(SystemConfig.class)

二:借助spring的工具类WebApplicationContextUtils

代码示例如下:

//普通类中
        ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();
        //使用request
        ServletContext sc = request.getServletContext();
        //通过webApplicationContextUtils获取ApplicationContext
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
        SystemConfig bean = ac.getBean(SystemConfig.class);

这种方法其实也是通过获取spring上下文ApplicationContext来拿到bean的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值