![](/img/trans.png)
[英]Spring:- what is the main difference between using @autowired annotation and using “autowire” in spring xml configuration?
[英]What is difference between these 2 Spring Annotation and XML config
这两个Spring Annotation和XML配置有什么区别
1)基于注释
@Configuration
@EnableWebMvc
public class MyWebConfig{
//
}
2)基于XML
<mvc:annotation-driven />
我看不出除xml和注释之外的任何其他区别。 什么时候使用哪一个?
基于注释的配置比xml中的等效配置更容易,更易读。 例如,在xml中将属性设置为map,如下所示:
<property name="maps">
<map>
<entry key="Key 1" value="1" />
<entry key="Key 2" value-ref="PersonBean" />
<entry key="Key 3">
<bean class="com.mkyong.common.Person">
<property name="name" value="mkyongMap" />
<property name="address" value="address" />
<property name="age" value="28" />
</bean>
</entry>
</map>
</property>
在java配置文件中,它看起来像这样:
Map<String, Object> maps = ...
maps.put()...
....setMaps(maps);
还有很多其他优点:
从匿名内部类型的实例添加bean
在开始Spring上下文和tomcat之前,请在编译期间查看错误...
在bean构造中添加一些条件
例如:
@Bean
public ViewResolver internalResourceViewResolver() {
ClassLoader classLoader = getClass().getClassLoader();
if (ClassUtils.isPresent("org.apache.tiles.TilesContainer", classLoader)) {
TilesViewResolver viewResolver = new TilesViewResolver();
return viewResolver;
} else {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
@Treydone写了一些例子,并表达了关于基于Java的配置更好的主观意见。
我不同意这种说法,因为基于Java的配置和XML配置之间没有功能差异,你只会习惯使用哪一个。 有人说传统的XML命名空间配置更好,其他人说基于Java的配置(从3.0开始是Spring)是Spring的下一级IoC。
BTW基于注解配置的是不一样的基于Java的一个-你从后者写道例子,所以我假设你是XML和Java之间CONFIGS选择。
我想你应该读:
然后决定哪一个最适合你。
基于PS注释的配置是IMO比这两者更糟的选择,因为它将一些依赖信息直接移动到普通类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.