SPRING IN ACTION 第4版笔记-第二章-001-用@Autowired\@ComponentScan、@Configuration、@Component实现自动装载bean
1.
1 package soundsystem; 2 import org.springframework.context.annotation.ComponentScan; 3 import org.springframework.context.annotation.Configuration; 4 5 @Configuration //说明此类是配置文件 6 //@ComponentScan //开启扫描,会扫描当前类的包及其子包 7 //@ComponentScan(basePackages={"soundsystem", "video"})//扫描多个包 8 @ComponentScan(basePackageClasses={CDPlayer.class})//指定要扫描的类 9 public class CDPlayerConfig { 10 }
2.
1 package soundsystem; 2 import org.springframework.beans.factory.annotation.Autowired; 3 import org.springframework.stereotype.Component; 4 5 @Component 6 public class CDPlayer implements MediaPlayer { 7 private CompactDisc cd; 8 9 @Autowired 10 public CDPlayer(CompactDisc cd) { //依赖bean的id会叫"cd"??? 11 this.cd = cd; 12 } 13 14 public void play() { 15 cd.play(); 16 } 17 18 }
3.
1 package soundsystem; 2 import org.springframework.stereotype.Component; 3 4 @Component 5 public class SgtPeppers implements CompactDisc { 6 7 private String title = "Sgt. Pepper's Lonely Hearts Club Band"; 8 private String artist = "The Beatles"; 9 10 public void play() { 11 System.out.println("Playing " + title + " by " + artist); 12 } 13 14 }
4.
1 package soundsystem; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Rule; 6 import org.junit.Test; 7 import org.junit.contrib.java.lang.system.StandardOutputStreamLog; 8 import org.junit.runner.RunWith; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.test.context.ContextConfiguration; 11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 13 @RunWith(SpringJUnit4ClassRunner.class) //会自动创建applicationcontext 14 @ContextConfiguration(classes=CDPlayerConfig.class)//指定配置文件 15 public class CDPlayerTest { 16 17 @Rule 18 public final StandardOutputStreamLog log = new StandardOutputStreamLog(); 19 20 @Autowired 21 private MediaPlayer player; //默认id会是“player”??? 22 23 @Autowired 24 private CompactDisc cd; 25 26 @Test 27 public void cdShouldNotBeNull() { 28 assertNotNull(cd); 29 } 30 31 @Test 32 public void play() { 33 player.play(); 34 assertEquals( 35 "Playing Sgt. Pepper's Lonely Hearts Club Band by The Beatles", 36 log.getLog()); 37 } 38 39 }
bean
You can do anything you set your mind to, man!