【问题标题】:Is it possible to use @Resource on a constructor?是否可以在构造函数上使用@Resource?
【发布时间】:2011-08-15 10:12:41
【问题描述】:

我想知道是否可以在构造函数上使用 @Resource 注释。

我的用例是我想连接一个名为 bar 的最终字段。

public class Foo implements FooBar {

    private final Bar bar;

    @javax.annotation.Resource(name="myname")
    public Foo(Bar bar) {
        this.bar = bar;
    }
}

我收到一条消息,指出此位置不允许使用 @Resource。有没有其他方法可以连接 final 字段?

【问题讨论】:

    标签: java spring autowired spring-annotations


    【解决方案1】:

    使用@Autowired@Inject。这个限制在Spring reference documentation: Fine-tuning annotation-based autowiring with qualifiers:

    @Autowired 适用于字段、构造函数和多参数方法,允许在参数级别通过限定符注释缩小范围。相比之下,@Resource 仅支持具有单个参数的字段和 bean 属性设置器方法。因此,如果您的注入目标是构造函数或多参数方法,请坚持使用限定符。

    【讨论】:

    • 我将@Autowired 与@Qualifier 注释一起使用。这是因为我有多个可以连接的实现。为了表达我需要哪种实现,我使用了限定符。在文档中,它声明在这种情况下更喜欢使用 @Resource 。所以我正在尝试这样做。
    • 哪个文档项目说@Resource 是首选?
    • 在官方文档中:static.springsource.org/spring/docs/2.5.x/reference/beans.html 下面的章节 3.11.3 作为提示!
    • 好点。在 Spring 3 文档中,这已被提炼为提到您遇到的问题,请在 static.springsource.org/spring/docs/3.0.x/reference/… 中查找提示
    【解决方案2】:

    来自@Resource的来源:

    @Target({TYPE, FIELD, METHOD})
    @Retention(RUNTIME)
    public @interface Resource {
        //...
    }
    

    这一行:

    @Target({TYPE, FIELD, METHOD})
    

    表示这个注解只能放在Classes、Fields和Methods上。 CONSTRUCTOR 不见了。

    【讨论】:

    • 该死的……我已经读了很多遍了,但是错过了……谢谢!所以我会回退到@Autowire 和@Qualifier。
    【解决方案3】:

    为了补充 Robert Munteanu 的回答并供将来参考,以下是在构造函数上使用 @Autowired@Qualifier 的外观:

    public class FooImpl implements Foo {
    
        private final Bar bar;
    
        private final Baz baz;
    
        @org.springframework.beans.factory.annotation.Autowired
        public Foo(Bar bar, @org.springframework.beans.factory.annotation.Qualifier("thisBazInParticular") Baz baz) {
            this.bar = bar;
            this.baz = baz;
        }
    }
    

    在这个例子中,bar 只是自动装配的(即上下文中只有一个该类的 bean,因此 Spring 知道要使用哪个),而 baz 有一个限定符来告诉 Spring 该类的哪个特定 bean我们要注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多