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;
}
}
I would just need to write this:
<beans ... >
<bean id="mailMan" class="MailMan">
<constructor-arg value="John Doe"/>
</bean>
<bean id="parcel" class="Parcel" />
<context:annotation-config />
</beans>
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;
}
}
By default, a Spring context will pay no attention to
@Autowiredannotations. In order to process them, the context needs to have aAutowiredAnnotationBeanPostProcessorbean registered in the context.<context:annotation-config/>registers one of these for you (along with a few others), so you do need it (unless you registerAutowiredAnnotationBeanPostProcessoryourself, which is perfectly valid).If you don’t like having
@Autowiredin your code, then you can explicitly inject properties in the XML using<property>, which just moves the clutter from one place to another.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.
@Autowiredreally is the best option, in general.