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

查看:76
本文介绍了@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?

推荐答案

根据Autowired 的 Javadoc,注解可用于构造函数、字段、设置方法或配置方法".请参阅 完整文档了解更多详情.

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;
    }

构造函数注入还允许您在单元测试中测试类,而无需依赖 Spring 的代码.

Constructor injection also allows you to test the class in a unit test without code that depends on Spring.

第二个选项最好写成:

@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 放在 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天全站免登陆