当前位置: 代码迷 >> 综合 >> spring boot 配置 获取spring 上下文用来自行获取bean操作
  详细解决方案

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

热度:65   发布时间:2023-10-26 19:43:30.0

第一步:实现 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;@Overridepublic 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)

  相关解决方案