我们知道,@Autowired
只能在spring容器管理的实例中使用,如果你new了一个实例,其中的@Autowired
成员是不会生效的。
但我认为在某些情况下,new an instance 是不可避免的。
例如 RunnableTask。其中包含由 spring 管理的 DAOService。因为任务是手动新建的。所以我不能在 ThreadTask 中使用 DAOService。
所以我想知道如何在Spring Boot中获取ApplicationContext,所以我可以通过context.getBean()
获取bean。
我知道在 main() 中我可以自动连接 ApplicationContext。但是我不能在所有地方将上下文作为参数传递!
我想在任何地方获取 ApplicationContext。
如有任何帮助,我们将不胜感激。
最佳答案
使用由 spring 管理的工厂对象怎么样?
class TheBeanYouWant {
private Integer beanSupposeToAutowired;
public TheBeanYouWant(Integer bean) {
this.beanSupposeToAutowired = bean;
}
}
@Component
class TheBeanFactory {
@Autowired
private Integer beanAutowired;
public TheBeanYouWant newBean() {
return new TheBeanYouWant(beanAutowired);
}
}
关于spring-boot - 如何在 Spring Boot 手动新建实例中使用@Autowired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26586932/