context:annotation-config 是@AutoWired 的替代品吗? [英] Is context:annotation-config an alternative to @AutoWired?

查看:39
本文介绍了context:annotation-config 是@AutoWired 的替代品吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将 context:annotation-config 放在我的 XML 配置中并且它会自动注入 bean 类而不需要任何注释是否正确?

Is it correct that I can put context:annotation-config in my XML config and it will automatically inject the bean class without needing any annotations?

所以不要使用这些注释类型:

So instead of using these annotation types:

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 类看起来会简单得多,不需要注释:

and then my MailMan class would look a lot simpler without the need for annotations:

public class Mailman
{
    private String name;

    private Parcel Parcel;

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

推荐答案

默认情况下,Spring 上下文不会关注 @Autowired 注释.为了处理它们,上下文需要在上下文中注册一个 AutowiredAnnotationBeanPostProcessor bean.

By default, a Spring context will pay no attention to @Autowired annotations. In order to process them, the context needs to have a AutowiredAnnotationBeanPostProcessor bean registered in the context.

<context:annotation-config/> 为您注册其中之一(以及其他一些),因此您确实需要它(除非您注册 AutowiredAnnotationBeanPostProcessor 你自己,这是完全正确的).

<context:annotation-config/> registers one of these for you (along with a few others), so you do need it (unless you register AutowiredAnnotationBeanPostProcessor yourself, which is perfectly valid).

如果您不喜欢在您的代码中使用 @Autowired,那么您可以使用 在 XML 中显式注入属性,这只会移动混乱从一个地方到另一个地方.

If you don't like having @Autowired in your code, then you can explicitly inject properties in the XML using <property>, which just moves the clutter from one place to another.

如果您的上下文非常,那么您可以使用隐式自动装配,如此处.本质上,这告诉 Spring 按属性名称或类型自动装配.这需要很少的配置,但很快就会失控——它的自动性质意味着它很难控制,并且给你的灵活性很小.

If your context is extremely simple, then you can use implicit autowiring, as described here. Essentially, this tells Spring to autowire automatically by property name or type. This required very little configuration, but it very quickly gets out of control - it's automatic nature means it's hard to control, and gives you very little flexibility.

@Autowired 确实是最好的选择,总的来说.

@Autowired really is the best option, in general.

这篇关于context:annotation-config 是@AutoWired 的替代品吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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