1 spring如何通过组件扫描和自动装配实现自动化的配置
1 首先将spring依赖的包全部导入
2 建立测试接口
public interface CompactDisc { void play(); }
3 具体的类实现接口
import org.springframework.stereotype.Component; import morningstar.spring.CompactDisc; /* * @Component 注解用在类上表明该类会作为组件类使用,并且告知spring要为这个类创建bean*/ @Component public class Stgpepers implements CompactDisc { private String title="sgt.peper's lnnely hearts club band"; private String artist="the beatles"; @Override public void play() { // TODO Auto-generated method stub System.out.println("playing "+title+" by "+artist); } }
4 创建配置类
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import morningstar.spring.entity.Stgpepers; @Configuration @ComponentScan(basePackages = {"morningstar.spring.entity"}) public class CDPlayerConfig { /* *@Configuration: *@ComponentScan:在spring中启用组件扫描 */ }
5 建立测试:
//SpringJUnit4ClassRunner:测试开始的时候就创建spring的应用上下文 @RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration注解告诉spring在CDPlayerConfig类中加载配置类 @ContextConfiguration(classes =CDPlayerConfig.class ) public class CDPlayerTest { @Autowired private CompactDisc disc; @Rule public final StandardErrorStreamLog log=new StandardErrorStreamLog(); @Autowired private MediaPlayer player; @Test public void cdShouldNotBeNull() { assertNotNull(disc); System.out.println("success"); } @Test public void player() { player.play(); } }
6 结果:
测试通过