Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

spring - Where is the @Autowired annotation supposed to go - on the property or the method?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...