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>
javaConfig:
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>
Spring JavaConfig是Spring社区的产品,它提供了一种纯Java方法来配置Spring IoC容器。因此,它有助于避免使用XML配置。