Search code examples
javaspringspring-bootspring-annotations

Purpose of using set method in below code snippet


I was going through the Spring tutorial and I found below code snippet:

public class EmployeeRestController {
    private Logger logger = LoggerFactory.getLogger(EmployeeRestController.class);

    @Autowired
    private EmployeeService employeeService;

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }
}

My Question is that Why this method is used even though the is no call of this method.:

public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

Thanks


Solution

  • I believe this setter method has no significance if you use spring dependency injection to set the dependency on a class property. That's what is happening to EmployeeRestController by using @Autowired annotation to employee service property private EmployeeService employeeService; You can also use setter level dependency injection this way

     @Autowired
     public void setEmployeeService(EmployeeService employeeService) {
            this.employeeService = employeeService;
        }
    

    It's a good and suggested practice to use @Autowired on setter instead of private properties.