创建一个工具类
@Component
public class SpringBeanOperator implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if(applicationContext == null){
applicationContext = context;
}
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
/**
* 注入对象
*/
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过名称注入
* /
public static final Object getBean(String beanName) {
return getApplicationContext().getBean(beanName);
}
}
使用
public class TestOperator {
//非Bean的类这样注入是空的
// @Autowired
// private TestService testService;
// @Autowired
// private TestManager testManager;
//使用工具类解决
private TestService testService= SpringBeanOperator.getBean(TestService .class);
private TestManager testManager = SpringBeanOperator.getBean(TestManager .class);
}
原有的采用@Autowired注入因为普通类无法注入
可以改为使用工具类获得它的bean对象
本文介绍了一种在SpringBoot中,对于非@Component注解的普通类如何实现依赖注入的方法。通过创建一个名为SpringBeanOperator的工具类,该类实现了ApplicationContextAware接口,能够获取到Spring的上下文,进而实现对任意类的注入。这种方式适用于那些不作为Spring Bean的类,但仍需使用Spring管理的依赖。文章提供了具体的代码示例,展示了如何在TestOperator类中使用此工具类来注入TestService和TestManager。

929

被折叠的 条评论
为什么被折叠?



