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

标签 spring-boot autowired applicationcontext

我们知道,@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/

相关文章:

java - @Recover(后备方法)与 @CircuitBreaker 一起使用时,一旦所有重试都用尽,就不会被调用

java - Spring Data Repository Autowiring 失败

hibernate - 在JSF2.0、Hibernate、MySQL中启用UTF-8字符集

java - 如何在intellij中运行spring boot应用程序?

java - 为 SendGrid 创建 JUnit 测试

java - Hibernate ManyToMany 方法抛出 'org.hibernate.LazyInitializationException' 异常

java - Spring 的@Autowired 如何与没有实现的接口(interface)一起工作?

java - 在没有 RequestMapping 的类中 Autowiring

java - 使用 @MockBean 来模拟具有 @BeforeStep 的 ItemReader 会向许多具有 @Beforestep 注释的方法抛出异常。我该如何解决?

java -eclipse-资源泄漏 : 'appContext' is never closed