导入和混合配置
1、拆分JavaConfig
@Configuration public class CDConfig { @Bean public CompactDisc compactDisc() { return new SgtPeppers(); } }
使用@Import注解
@Configuration @Import(CDConfig.class) public class CDPlayerConfig { @Bean public CDPlayer cdPlayer(CompactDisc compactDisc) { return new CDPlayer(compactDisc); } }
或使用一个更高级别的JavaConfig引用2个JavaConfig
@Configuration @Import({ CDPlayerConfig.class, CDConfig.class }) public class SoundSystemConfig { }
2、JavaConfig中引用XML配置
1中把CDPlayer和CompactDisc分开了,假设出于某些原因,需要把CompactDisc用XML来配置
<bean id="compactDisc" class="soundsystem.BlankDisc" c:_0="Sgt. Pepper‘s Lonely Hearts Club Band" c:_1="The Beatles"> <constructor-arg> <list> <value>Sgt. Pepper‘s Lonely Hearts Club Band</value> <value>With a Little Help from My Friends</value> <value>Lucy in the Sky with Diamonds</value> <value>Getting Better</value> <value>Fixing a Hole</value> <!-- ...other tracks omitted for brevity... --> </list> </constructor-arg> </bean>
JavaConfig引用XML配置
@Configuration @Import(CDPlayerConfig.class) @ImportResource("classpath:cd-config.xml") public class SoundSystemConfig { }
这样,CDPlayer和BlankDisc都会作为bean被加载到Spring容器中;而CDPlayer添加了@Bean注解,所需参数CompactDisc也会把BlanDisc加载进来
3、拆分XML配置
<import resource="cd-config.xml" /> <bean id="cdPlayer" class="soundsystem.CDPlayer" c:cd-ref="compactDisc" />
4、XML配置中引用JavaConfig
<bean class="soundsystem.CDConfig" /> <bean id="cdPlayer" class="soundsystem.CDPlayer" c:cd-ref="compactDisc" />
推荐无论使用JavaConfig还是XML配置,都加入一个更高层次的配置文件,负责组合这些配置文件
<bean class="soundsystem.CDConfig" /> <import resource="cdplayer-config.xml" />