views:

101

answers:

2

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?

A: 

The annotation goes with the property, because that's what's being autowired; the property to be automatically set. This tutorial has a nice example. This more advanced example shows how to use qualifiers to disambiguate the wiring.

dj_segfault
+3  A: 

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.

NamshubWriter