CD唱片的接口:
package v4.c2; public interface CompactDisc { void play(); }
CD实现类:
package v4.c2; public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles"; public void play() {
System.out.println("Playing " + title + " by " + artist);
} }
播放器接口
package v4.c2; public interface MediaPlayer { void play(); }
播放器实现类:
package v4.c2;
import org.springframework.beans.factory.annotation.Autowired; public class CDPlayer implements MediaPlayer {
private CompactDisc cd; @Autowired
public CDPlayer(CompactDisc cd) {
this.cd = cd;
} public void play() {
cd.play();
} }
CD配置类:
package v4.c2; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class CDConfig {
@Bean
public CompactDisc compactDisc() {
System.out.println(2222);
return new SgtPeppers();
}
}
播放器的配置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="v4.c2.CDConfig" /> <bean id="cdPlayer"
class="v4.c2.CDPlayer"
c:cd-ref="compactDisc" /> </beans>
注意这里就是在xml配置中引用java配置
<bean class="v4.c2.CDConfig" />
现在用ClassPathXmlApplicationContext测试
package v4.c2; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Boot { public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("v4/c2/cdplayer-config.xml");
MediaPlayer media = ac.getBean(MediaPlayer.class);
media.play();
ac.close();
} }
报错:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'compactDisc' available
换成AnnotationConfigApplicationContext的方式,要添加一个根配置类:
package v4.c2; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource; @Configuration
@ImportResource("classpath:v4/c2/cdplayer-config.xml")
public class SoundSystemConfig { }
这样测试:
package v4.c2; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Boot { public static void main(String[] args) { AnnotationConfigApplicationContext ac =new AnnotationConfigApplicationContext(SoundSystemConfig.class);
MediaPlayer media = ac.getBean(MediaPlayer.class);
media.play();
ac.close();
} }
成功,输出:
2222
Playing Sgt. Pepper's Lonely Hearts Club Band by The Beatles