对于总是固执地使用Spring的XML配置方式,同事们总是讥讽我。是的,这看起来太二太过时了,不过XML还是有它的优势:
1.集中式配置。这样做不会将不同组件分散的到处都是。你可以在一个地方看到所有Bean的概况和他们的装配关系。
2.如果你需要分割配置文件,没问题,Spring可以做到。它可以在运行时通过<import>标签或者上Context文件对分割的文件进行重新聚合。
3.相对于自动装配(autowiring),只有XML配置允许显示装配(explicit wiring)
4.最后一点并不代表不重要,XML配置完全和JAVA文件解耦:两种文件完全没有耦合关系,这样的话,类可以被用作多个不同XML配置文件。
XML唯一的问题是,只有在运行时环境时你才能发现各种配置及语法错误,但是如果使用Spring IDE Plugin(或者STS)的话,它会在编码时提示这些问题。
在XML配置和直接注解式配置之外还有一种有趣的选择方式-JavaConfig,它是在Spring 3.0开始从一个独立的项目并入到Spring中的。它结合了XML的解耦和JAVA编译时检查的优点。JavaConfig可以看成一个XML文件,只不过是使用Java编写的。相关文档在官方网站是可以找到的,这篇文章只是带你了解JavaConfig。下面的例子,让我们将从XMl文件移植到JavaConfig。
XML配置文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
- <bean id="button" class="javax.swing.JButton">
- <constructor-arg value="Hello World" />
- </bean>
- <bean id="anotherButton" class="javax.swing.JButton">
- <property name="icon" ref="icon" />
- </bean>
- <bean id="icon" class="javax.swing.ImageIcon">
- <constructor-arg>
- <bean class="java.net.URL">
- <constructor-arg value="http://morevaadin.com/assets/images/learning_vaadin_cover.png" />
- </bean>
- </constructor-arg>
- </bean>
- </beans>
- import java.net.MalformedURLException;
- import java.net.URL;
- import javax.swing.Icon;
- import javax.swing.ImageIcon;
- import javax.swing.JButton;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- public class MigratedConfiguration {
- @Bean
- public JButton button() {
- return new JButton("Hello World");
- }
- @Bean
- public JButton anotherButton(Icon icon) {
- return new JButton(icon);
- }
- @Bean
- public Icon icon() throws MalformedURLException {
- URL url = new URL(
- "http://morevaadin.com/assets/images/learning_vaadin_cover.png");
- return new ImageIcon(url);
- }
- }
1.用@Configuration注解JavaConfig类,
2.用每个方法来表示Bean并使用@Bean注解方法。
3.每个方法名代表XML配置文件中的name
注意在Web环境中,需要在web.xml中加入如下代码:
- <context-param>
- <param-name>contextClass</param-name>
- <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
- </context-param>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>com.packtpub.learnvaadin.springintegration.SpringIntegrationConfiguration</param-value>
- </context-param>
相关资源:
·AnnotationConfigWebApplicationContext JavaDoc
·@ContextConfiguration JavaDoc(to configure Spring Test to use JavaConfig)