上一次的随笔内容只是简单的实现了Bean的装配(依赖注入)java
今天来具体讲讲实现Bean装配的三种经常使用方法:spring
自动化装配app
使用javaConfig显示装配ide
使用xml装配测试
通常来讲,尽量地使用自动化装配(spring的一大原则就是约定大于配置),在必要时使用javaConfig显示装配,实在不行才使用xml装配this
本篇不涉及xml装配spa
1、自动化装配code
所谓自动化装配,就是让spring自动的发现上下文所建立的Bean,并自动知足这些Bean之间的依赖。xml
自动扫描须要在Config配置类里加上@ComponentScan注解:blog
@Configuration //@PropertySource("classpath:./test/app.properties") @ComponentScan public class CDPlayerConfig { // @Autowired // Environment env; // // @Bean // @Conditional(CDExistsCondition.class) // public CDPlayer cdPlayer(CompactDisc compactDisc){ // return new CDPlayer(compactDisc); // } // // @Bean //// @Primary // public CompactDisc sgtPeppers(){ // return new BlankDisc(); //// return new SgtPeppers(); // } // // @Bean // public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){ // return new PropertySourcesPlaceholderConfigurer(); // } // // @Bean // @Primary // public CompactDisc BeatIt(){ // return new BeatIt(); // } }
若是不须要再显示配置Bean,那么配置类里能够是空的,彻底交给Spring去自动配置。
既然要让spring自动发现Bean,那么在写类的时候,咱们便要加上@Component注解,表示这是一个能够被发现的Bean:
package CD_Play; import org.springframework.stereotype.Component; @Component("abc") public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band"; private String artist = "The Beatles"; SgtPeppers(){} @Override public void play() { System.out.println("Playing " + title + " by " + artist); } }
这里类是一张“CD”,他实现了CD接口,并具备play功能,咱们正准备把他放入“CD机”(CDPlayer)进行播放,如今咱们为这个类加上了@Component注解,他就能够被Spring自动扫描发现了。
如今Spring已经能够发现这个类了,那么要怎么才能让Spring直到这个类该装配到哪里去呢,这就须要咱们在须要装配的地方加上@Autowired注解:
package CD_Play; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class CDPlayer implements MediaPlayer{ private CompactDisc cd; @Autowired CDPlayer(CompactDisc cd){ this.cd = cd; } // @Autowired // @Qualifier("abc") // public void setCd(CompactDisc cd) { // this.cd = cd; // } // public CDPlayer(CompactDisc cd){ // this.cd = cd; // } @Override public void play() { cd.play(); } }
这个@Autowired注解能够加载构造器上,也能够加载set方法上(如注释中同样),这样Spring就会根据所须要的参数(这里是CompactDisc类的参数)从建立好各个Bean的容器中找到匹配这个类型的Bean直接装配进去。
最后放出测试类进行测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CDPlayerConfig.class) public class CDPlayerTest{ @Rule public final StandardOutputStreamLog log = new StandardOutputStreamLog(); @Autowired private MediaPlayer player; @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull(){ assertNotNull(cd); } @Test public void play(){ player.play(); assertEquals("Playing Sgt. Pepper's Lonely Hearts Club Band" + " by The Beatles\r\n", log.getLog()); } }
测试结果为:
能够看到测试经过,证实Bean已被建立并被正确的装配到CDPlayer中正常工做。