如何在 Spring Boot 中手动新建实例中使用 @Autowired

Nin*_*Lee 2 autowired applicationcontext spring-boot

我们知道,@Autowired只能在spring容器管理的实例中使用,如果你新建一个实例,其中的@Autowired成员不会生效。

但我认为在某些情况下,新实例无法避免。

比如一个RunnableTask。其中包含由 spring 管理的 DAOService。因为任务是手动新建的。所以我不能在ThreadTask中使用DAOService。

所以我想知道如何在Spring Boot 中获取 ApplicationContext ,这样我就可以通过context.getBean().

我知道在 main() 中我可以自动装配 ApplicationContext。但是我不能在任何地方都将上下文作为参数传递!

我想在任何地方获取 ApplicationContext。

任何帮助将不胜感激。

小智 5

使用 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);
     }
}
Run Code Online (Sandbox Code Playgroud)