简体   繁体   中英

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 (?).

Now I have to move ExpenseCalculator a configuration class (it doesn't have @Component annotation)

@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.

Is there any way to get lazy initialization of purchaseService using configuration ?

You must annotate your PurchaseService with @Lazy in both places - where you create them and when you autowire them. See https://www.baeldung.com/spring-lazy-annotation#2-with-autowired , comment: "Note, that the @Lazy is mandatory in both places."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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