使用JavaConfig替代XML配置

XML的优势:
1.集中式配置。这样做不会将不同组件分散的到处都是。你可以在一个地方看到所有Bean的概况和他们的装配关系。
2.如果你需要分割配置文件,没问题,Spring可以做到。它可以在运行时通过标签或者上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编写的。
XML配置文件:

 
 
  
     
         
     
  
     
         
     
  
     
         
             
               
             
         
     

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中加入如下代码:


    contextClass
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext


    contextConfigLocation
    com.packtpub.learnvaadin.springintegration.SpringIntegrationConfiguration

你可能感兴趣的:(使用JavaConfig替代XML配置)