我有一个组件
@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/