spring boot 配置 获取spring 上下文用来自行获取bean操作

本文介绍了一种通过实现ApplicationContextAware接口并结合使用@Component注解的方法来完成Spring Bean的注入过程。具体步骤包括定义静态ApplicationContext变量、实现setApplicationContext方法及提供获取Bean的静态方法。此外还提到了如何解决ApplicationContext在项目启动初期为空的问题。

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

第一步:实现 ApplicationContextAware接口

第二步:给类加上注解 @Component 让spring识别并且注入

第三步:定义好静态的 ApplicationContext ,在ApplicationContextAware实现的   setApplicationContext赋值过去;

后面就是自己根据自己的需求定义获取bean的接口

如:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by Lee on 2018/5/7.
 */
@Component
public class DemoApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("我已经注入啦");
            context=applicationContext;
    }
    public static <T> T getBean(Class<T> tClass){
        if(null==context){
            return null;
        }
        return context.getBean(tClass);
    }
}

注:如果项目启动后ApplicationContext为空的话,可能是项目配置了全局spring bean的懒加载功能,这时候就需要在类上加个注解: @Lazy(value=false)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值