According to the Javadoc for Autowired, the annotation can be used on "a constructor, field, setter method or config method". See the full documentation for more details.
I personally prefer your first option (constructor injection), because the myDao
field can be marked as final:
@Controller
public class MyControllear {
private final MyDao myDao;
@Autowired
public MyController(MyDao myDao) {
this.myDao = myDao;
}
Constructor injection also allows you to test the class in a unit test without code that depends on Spring.
The second option would be better written as:
@Controller
public class MyControllear {
@Autowired
private MyDao myDao;
MyController() {
}
With field injection, Spring will create the object, then update the fields marked for injection.
One option you didn't mention was putting @Autowired
on a setter method (setter injection):
@Controller
public class MyControllear {
private MyDao myDao;
MyController() {
}
@Autowired
public void setMyDao(MyDao myDao) {
this.myDao = myDao;
}
You do not have to choose one or another. You can use field injection for some dependencies and constructor injection for others for the same object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…