java - 使用构造函数在配置中进行 Spring 延迟初始化

标签 java spring lazy-initialization

我有一个组件

@Component
public class ExpenseCalculator {
    @Autowired
    private TaxService taxService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    @Lazy
    private PurchaseService purchaseService;
}

此处,仅当调用使用 purchaseService 的代码的任何部分时才会初始化 PurchaseService(?)。

现在我必须移动ExpenseCalculator配置类(它没有@Component注释)

@Configuration
public class ExpenseConfig {
    @Bean
    @Lazy
    public ExpenseCalculator getExpenseCalculator(
        TaxService taxService, 
        EmployeeService employeeService,
        PurchaseService purchaseService
    ) {
        return new ExpenseCalculator(taxService, employeeService, purchaseService);
    }
} 

但是,当 ExpenseCalculator 初始化时,purchaseService 不再是 @Lazy 组件,purchaseService 也会被初始化。

有没有办法使用configuration来延迟初始化purchaseService

最佳答案

您必须在创建它们的位置和 Autowiring 它们的位置都使用 @Lazy 注释您的 PurchaseService

请参阅A Quick Guide to the Spring @Lazy Annotation帖子,在 2.2. With @Autowired部分存在评论:

Note, that the @Lazy is mandatory in both places.

关于java - 使用构造函数在配置中进行 Spring 延迟初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62508723/

相关文章:

java - 为什么它会跳过数组索引 0?

java - 仅在开发环境中使用 Spring 过滤器

java - 无法初始化代理 - 无 session 异常

java - 顺序读取文件时出现 NumberFormatException?

Java Json数据传输

java - 如何与 Maven 一起运行 xml 配置驱动和无 xml Spring Web 应用程序?

c++ - 在 C++ 中是否可以进行热切的 thread_local 初始化?

java - 在 spring 中使用 Apache cxf 拦截器和 log4j 记录完整的请求和响应

java - 在 Spring mvc 中使用 html 文件发送 dto

F# 等效于具有案例类/可区分联合的 Scala lazy val