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

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

推荐答案

据<一个href=\"http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html\">the Javadoc文档自动装配,注释可以在构造函数,字段setter方法​​或者配置方法中使用。见<一href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-autowired-annotation\">the完整的文档了解更多详细信息。

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.

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

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

构造方法注入,您还可以测试在单元测试的类,而不code依赖于Spring。

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 上一个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天全站免登陆