假设你正在使用Spring基于XML的配置并且你已经意识到XML逐渐变得无法控制,我们决定将XML配置文件进行拆分。
例如如下cdplayer_config.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" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sgtPeppers" class="com.yhw.SgtPeppers"></bean>
<bean id="cdPlayer" class="com.yhw.CDPlayer">
<c:cd-ref="sgtPeppers"/>
</bean>
</beans>
配置类两个bean,其中CDPlayer类需要依赖SgtPeppers类。现在将SgtPeppers类拆分为JavaConfig如下:
@Configuration
public class CDPlayerConfig {
@Bean
public CompactDisc stgPeppers(){
return new SgtPeppers();
}
}
而CDPlayer则继续留在xml中配置,那么基于xml配置该如何引用一个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" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.yhw.CDPlayerConfig"></bean>
<bean id="cdPlayer" class="com.yhw.CDPlayer">
<c:cd-ref="sgtPeppers"/>
</bean>
</beans>
采用这种方式,两种配置–一个使用xml描述,另一个使用Java描述–被组合到了以起。当然还可以创建一个更高层次的配置文件,这个文件不声明任何的bean,只负责将两个或更多个配置组合起来。例如将上面xml配置文件和JavaConfig配置结合起来:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.yhw.CDPlayerConfig"></bean>
<import resource="com.yhw.cdplayer_config.xml"/>
</beans>
不管使用JavaConfig还是使用XML进行装配bean,通常会创建一个根配置(root configuration)也就是上面展现的一样,这个配置将两个或多个装配类或XML文件组合起来,也可以在根配置中启用组件扫描(通过context:component-scan或@ComponentScan)。