Which is more correct?
This (with the @Autowired annotation on the method)?
@Controller
public class MyController
{
private MyDao myDao;
@Autowired
public MyController(MyDao myDao)
{
this.myDao = myDao;
}
This (with the @Autowired annotation on the property)?
@Controller
public class MyController
{
@Autowired
private MyDao myDao;
public MyController(MyDao myDao)
{
this.myDao = myDao;
}
Where is the @Autowired annotation supposed to go?
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
myDaofield can be marked as final: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:
With field injection, Spring will create the object, then update the fields marked for injection.
One option you didn’t mention was putting
@Autowiredon a setter method (setter injection):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.