Reputation: 961
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
Upvotes: 0
Views: 49
Reputation: 524
if you have used @Autowired then no requirement of setmethod so refer below code:
@Controller
public class EmployeeRestController {
private Logger logger = LoggerFactory.getLogger(EmployeeRestController.class);
@Autowired
private EmployeeService employeeService;
}
@Service
public class EmployeeService{
}
Upvotes: 0
Reputation: 4988
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.
Upvotes: 1