I'm using Spring since a few months for now, and I thought dependency injection with the @Autowired
annotation also required a setter for the field to inject.
So, I am using it like this:
@Controller
public class MyController {
@Autowired
MyService injectedService;
public void setMyService(MyService injectedService) {
this.injectedService = injectedService;
}
...
}
But I've tried this today:
@Controller
public class MyController {
@Autowired
MyService injectedService;
...
}
And oh surprise, no compilation errors, no errors at startup, the application is running perfectly...
So my question is, is the setter required for dependency injection with the @Autowired
annotation?
I'm using Spring 3.1.1.
You don't need a setter with the @Autowired, the value is set by reflection.
Check this post for complete explanation How does Spring @Autowired work