context:annotation-config是@AutoWired的替代方案吗?

7

我可以在我的XML配置文件中添加context:annotation-config,这样就可以自动注入bean类而不需要任何注释,这种说法正确吗?

因此,可以不使用以下这些注释类型:

public class Mailman
{
    private String name;

    @Autowired
    private Parcel Parcel;

    public Mailman(String name)
    {
        this.name = name;
    }

    @Autowired
    public void setParcel(Parcel Parcel)
    {
        this.Parcel = Parcel;
    }

    @Autowired
    public void directionsToParcel(Parcel Parcel)
    {
        this.Parcel = Parcel;
    }

}

我只需要写这个:
<beans ... >
<bean id="mailMan" class="MailMan">
 <constructor-arg value="John Doe"/>
</bean>
<bean id="parcel" class="Parcel" />
<context:annotation-config />
</beans>

如果不需要注解,我的MailMan类会变得更加简单:

public class Mailman
{
    private String name;

    private Parcel Parcel;

    public Mailman(String name)
    {
        this.name = name;
    }    
}
3个回答

7
默认情况下,Spring上下文将不会注意到@Autowired注释。为了处理它们,上下文需要在上下文中注册一个AutowiredAnnotationBeanPostProcessor bean。 <context:annotation-config/> 为您注册其中之一(以及其他一些),因此您确实需要它(除非您自己注册AutowiredAnnotationBeanPostProcessor,这是完全有效的)。
如果您不喜欢在代码中使用@Autowired,则可以使用<property>在XML中显式注入属性,这只是将混乱从一个地方移动到另一个地方。
如果您的上下文非常简单,则可以使用隐式自动装配,如here所述。基本上,这告诉Spring按属性名称或类型自动装配。这需要很少的配置,但很快就会失去控制 - 它的自动性意味着很难控制,并且给您很少的灵活性。

@Autowired通常是最好的选择。


1

<context:annotation-config /> 只是自动注册了Spring提供的所有标准bean后处理器,例如PersistenceAnnotationBeanPostProcessorAutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessorRequiredAnnotationBeanPostProcessor,因此您不必在Spring上下文文件中单独注册它们。但是,您仍然需要像以前一样在属性/设置器上提供@Autowired注释。


0

不需要。

@Autowired注释需要与<context:annotation-config/>一起放在类上。

当使用注释时,不需要xml配置部分。

此外,从文档中可以看出,<context:annotation-config/>仅查找同一应用程序上下文中的bean上的注释。这意味着,如果您将其放置在DispatcherServlet的WebApplicationContext中,则仅检查控制器中的@Autowired bean,而不是服务中的@Autowired bean。

如果您不需要使用注释,则需要指定xml配置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接