@Autowired注释应该在哪里 - 属性或方法? [英] Where is the @Autowired annotation supposed to go - on the property or the method?

查看:211
本文介绍了@Autowired注释应该在哪里 - 属性或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更正确?

这(在方法中使用@Autowired注释)?

This (with the @Autowired annotation on the method)?

@Controller
public class MyController
{
    private MyDao myDao;

    @Autowired
    public MyController(MyDao myDao)
    {
        this.myDao = myDao;
    }

这(在属性上带有@Autowired注释)?

This (with the @Autowired annotation on the property)?

@Controller
public class MyController
{
    @Autowired
    private MyDao myDao;

    public MyController(MyDao myDao)
    {
        this.myDao = myDao;
    }

@Autowired注释应该在哪里?

Where is the @Autowired annotation supposed to go?

推荐答案

根据用于自动连线的Javadoc ,该注释可以在构造函数,字段,setter方法或配置方法上使用。请参阅完整文档更多的细节。

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.

我个人更喜欢你的第一个选项(构造函数注入),因为 myDao 字段可以标记为final:

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() {
    }

通过字段注入, Spring将创建对象,然后更新标记为注入的字段。

With field injection, Spring will create the object, then update the fields marked for injection.

您没有提到的一个选项是将 @Autowired on setter方法(setter注入):

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.

这篇关于@Autowired注释应该在哪里 - 属性或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆