前言
关于注解和xml配置的官方回答
Are annotations better than XML for configuring Spring?
The introduction of annotation-based configurations raised the question of whether
this approach is 'better' than XML. The short answer is it depends. The long
answer is that each approach has its pros and cons, and usually it is up to the
developer to decide which strategy suits them better. Due to the way they are
defined, annotations provide a lot of context in their declaration,
leading to shorter and more concise configuration. However, XML excels at
wiring up components without touching their source code or recompiling them.
Some developers prefer having the wiring close to the source while others
argue that annotated classes are no longer POJOs and, furthermore,
that the configuration becomes decentralized and harder to control.
No matter the choice, Spring can accommodate both styles and even mix them
together. It’s worth pointing out that through its JavaConfig option, Spring
allows annotations to be used in a non-invasive way, without touching the
target components source code and that in terms of tooling, all configuration
styles are supported by the Spring Tool Suite.
两种注解的说明
@autowired
简介
autowired是spring官方提供的一种装配方式。
使用方法
1.使用在方法上:
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
2.使用在字段上
@Autowired
private MovieCatalog movieCatalog;
说明
autowired主要是用bytype的方式注入。
@Resource
简介
@resource是java自带的一种装配方式。
使用方法
与@autowired相似
1.指定name属性
@Resource(name="myMovieFinder")
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
2.默认[使用默认提供名称]
@Resource
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
说明
@Resource默认按名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行名称查找。
总结
两种方式的功能大致相同,默认推荐使用@Resource方式,这是j2ee生的方式。能降低和spring的耦合度。
更多具体详情请参见官方:http://spring.io