javax.inject.Named 注释应该用于什么? [英] What is javax.inject.Named annotation supposed to be used for?

查看:64
本文介绍了javax.inject.Named 注释应该用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解 javax.inject 包,但我不清楚 javax.inject.Named 注释应该用于什么.Javadoc 没有解释它背后的想法.

I am trying to understand the javax.inject package and I am not clear what the javax.inject.Named annotation is supposed to be used for. The Javadoc does not explain the the idea behind it.

Javadoc 位于 http://download.oracle.com/javaee/6/api/javax/inject/Named.html

Javadoc is at http://download.oracle.com/javaee/6/api/javax/inject/Named.html

我正在使用 Spring 3.0 编写一些示例程序,通过将 @Named 放在一个 bean 上,它似乎将它添加到 bean 工厂中,但 Javadoc 描述是如此我不知道这是标准行为还是 Spring 特定行为.

I am using Spring 3.0 to write some sample programs, by putting @Named on a bean it seems to add it to the bean factory but the Javadoc description is so light I can't tell if that is the standard behavior or Spring specific behavior.

我的问题是:

  1. @Named@Qualifier 有什么区别
  2. 你应该如何告诉运行时系统一个类应该可以注入到其他类中?对此的注释是什么?相当于 Spring 中的 @Component 吗?
  1. What is the difference between @Named and @Qualifier
  2. How are you supposed to tell the Runtime system a class should be injectable in other classes what's the annotation for that? The equivalent of @Component in Spring?

更新 1 在关于 @Named 的 Nice 文章中对 @Named@Qualifier 有很好的解释和 @Qualifier https://dzone.com/articles/java-ee6-cdi-named-components 感谢@xmedeko 将下面的评论链接到它.

Update 1 there is an excellent explanation of @Named and @Qualifier at Nice article about @Named and @Qualifier https://dzone.com/articles/java-ee6-cdi-named-components thanks @xmedeko for linking to it the comment below.

推荐答案

使用 @Named区分绑定在同一范围内的相同类型的不同对象.

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

如果没有 @Named 限定符,注入器将不知道要绑定到哪个变量.

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • 如果您想创建类似于 @Named 的注释,请在创建时使用 @Qualifier 注释.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

如果你看@Named,它本身是用@Qualifier 注释的.

If you look at @Named, it is itself annotated with @Qualifier.

这篇关于javax.inject.Named 注释应该用于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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