Spring 3 中的 @Autowired 注解行为
我想了解 @Autowired 注释到底是如何工作的。
import com.test.WorkFlowDAO;
public class ServiceCentralBOImpl implements IServiceCentralBO
{
/**
* Logger for logging functionality.
*/
private static final Log log = LogFactory.getLog(ServiceCentralBOImpl.class);
@Autowired
private WorkFlowDAO workFlowDAO;
.
.
.
}
并且该 bean 是在我的 Spring applicationContext.xml 文件中声明的:
<bean id="workflowDAO" class="com.test.WorkFlowDAO">
</bean>
仔细检查后,您可以看到 Java 类和上下文 XML 文件中的两个 ID 是不同的。
workFlowDAO 和
workflowDAO
[两个 ID 中的字母“f”不同]
因为即使使用此配置,我的应用程序也可以正常运行;我想知道, @Autowired 注解如何工作,以便在 bean ID 不完全匹配时不会抱怨。
在简单使用bean的情况下; Spring 会抱怨 bean 名称不匹配。
我正在 Websphere App Server 7.0 上使用 Spring 3.0.5 运行 J2EE 应用程序,
如果需要更多信息,请告诉我。
I wanted to understand how exactly the @Autowired annotation works.
import com.test.WorkFlowDAO;
public class ServiceCentralBOImpl implements IServiceCentralBO
{
/**
* Logger for logging functionality.
*/
private static final Log log = LogFactory.getLog(ServiceCentralBOImpl.class);
@Autowired
private WorkFlowDAO workFlowDAO;
.
.
.
}
and the bean is declared in my Spring applicationContext.xml file:
<bean id="workflowDAO" class="com.test.WorkFlowDAO">
</bean>
Upon closer inspection you can see the two IDs in the Java class and the context XML file are different.
workFlowDAO and
workflowDAO
[The letter 'f' is different in the two IDs]
Since my application runs just fine even with this configuration; I wanted to know,
how does @Autowired
annotation work so that it does not complain when the bean IDs do not match exactly.
In case of simple bean usage; Spring would have complained of mismatching bean names.
I am running a J2EE application with Spring 3.0.5 on Websphere App Server 7.0
Let me know if any more information is required.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Autowired
按类型匹配 Bean。不考虑 ID。如果您在 XML 配置中声明另一个相同类型的 bean,Spring 会抱怨无法确定正确的 bean。
如果您想将 ID 与
@Autowired
一起使用,则可以使用@Qualifier
来实现,尽管在这种情况下建议使用@Resource
。查找有关该主题的更多信息 这里。
@Autowired
matches the beans by type. The ID is not considered.If you declare another bean of the same type in your XML configuration, Spring would complain about not being able to determine the correct bean.
If you want to use IDs together with
@Autowired
you can do so by utilizing@Qualifier
although@Resource
is recommended in this case.Find some more info on that topic here.
完全同意第一条评论。
如果您希望您的 bean 按名称自动装配,您可以考虑使用 @Qualifier("givenName")。
有关所有详细信息,请参阅:
http:// static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html
Completely agree with the first comment.
If you want your beans to be autowired by name, you may consider using @Qualifier("givenName").
See for all details:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html