Difference between autowired and using new keyword on autowired class in spring boot?

Viewed 58
@Autowired
private EmployeeService employeeService;

vs

@Autowired
private EmployeeService employeeService = new EmployeeService();

Is using new EmployeeService() on autowired class different than just using new EmployeeService()?

1 Answers

If a bean for @Autowired is injected it will override your created object. But if there is no bean created you have a fallback (in this case new EmployeeService(). That might be helpful for tests but it's kind of an anti-pattern because normally you just want one of both behaviours.

Related