简体   繁体   English

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

[英]Spring lazy initialization in configuration with constructor

I have a component我有一个组件

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

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    @Lazy
    private PurchaseService purchaseService;
}

Here PurchaseService is initialized only when any part of the code that uses purchaseService is invoked (?).这里PurchaseService仅在调用使用purchaseService的代码的任何部分时才被初始化(?)。

Now I have to move ExpenseCalculator a configuration class (it doesn't have @Component annotation)现在我必须将ExpenseCalculator移动一个配置 class (它没有@Component注释)

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

But purchaseService is no more a @Lazy component when ever ExpenseCalculator is initialized, purchaseService get initialized.但是,当ExpenseCalculator被初始化时, purchaseService不再是@Lazy组件, purchaseService被初始化。

Is there any way to get lazy initialization of purchaseService using configuration ?有什么方法可以使用configuration来延迟初始化purchaseService吗?

You must annotate your PurchaseService with @Lazy in both places - where you create them and when you autowire them.您必须在两个地方都使用 @Lazy 注释您的 PurchaseService - 创建它们的位置以及自动装配它们的时间。 See https://www.baeldung.com/spring-lazy-annotation#2-with-autowired , comment: "Note, that the @Lazy is mandatory in both places."请参阅https://www.baeldung.com/spring-lazy-annotation#2-with-autowired ,评论:“请注意,@Lazy 在这两个地方都是强制性的。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM