简体   繁体   English

Spring 3中的@Autowired注释行为

[英]@Autowired annotations behavior in Spring 3

I wanted to understand how exactly the @Autowired annotation works. 我想了解@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;
    .
    .
    .
}

and the bean is declared in my Spring applicationContext.xml file: 并且在我的Spring applicationContext.xml文件中声明了该bean:

<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. 通过仔细检查,您可以看到Java类中的两个ID和上下文XML文件是不同的。

workFlowDAO and workFlowDAO

workflowDAO workflowDAO

[The letter 'f' is different in the two IDs] [两个ID中的字母'f'不同)

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. 我想知道@Autowired批注如何工作,以便在bean ID不完全匹配时不会抱怨。

In case of simple bean usage; 如果使用简单的bean; Spring would have complained of mismatching bean names. Spring本来会抱怨bean名称不匹配。

I am running a J2EE application with Spring 3.0.5 on Websphere App Server 7.0 我正在Websphere App Server 7.0上运行带有Spring 3.0.5的J2EE应用程序

Let me know if any more information is required. 让我知道是否需要更多信息。

@Autowired matches the beans by type. @Autowired按类型匹配bean。 The ID is not considered. 不考虑ID。

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. 如果您在XML配置中声明了另一个相同类型的bean,Spring将抱怨无法确定正确的bean。

If you want to use IDs together with @Autowired you can do so by utilizing @Qualifier although @Resource is recommended in this case. 如果要将ID与@Autowired一起使用,则可以通过@Qualifier来使用,尽管在这种情况下建议使用@Resource

Find some more info on that topic here . 此处找到有关该主题的更多信息。

Completely agree with the first comment. 完全同意第一条评论。

If you want your beans to be autowired by name, you may consider using @Qualifier("givenName"). 如果希望按名称自动连接bean,则可以考虑使用@Qualifier(“ givenName”)。

See for all details: 查看所有详细信息:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM