Using the @Lazy annotation

Another workaround is to use the @Lazy annotation. This annotation will instruct Spring to load the bean only when it is used, instead of at the time of context loading. Spring will create a proxy of the bean during context loading and will pass it into another object. The updated code will look as follows:

@Component("employee")public class Employee {  private HRService hrService;  public Employee(@Lazy HRService hrService) {    this.hrService=hrService;  }  public void displayEmployeeName() {    System.out.println(" Employee name is Nilang ");  }}@Component("hrService")public class HRService {  private CommonUtilService commonUtilService;  public HRService(@Lazy CommonUtilService commonUtilService) { this.commonUtilService=commonUtilService; ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.