标签:cdn ora framework sys layer ... 声明 创建 autowire
1、添加dependencies如下所示(不是每一个都用得到
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
2、创建可以被发现的“ bean ”
首先定义CD的概念
package soundsystem; public interface CompactDisc { void play(); }
创建带有 @Component 注解的实现类
package soundsystem; import org.springframework.stereotype.*; @Component 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); } }
@Component 注解的作用
3、声明组件扫描,下面这个类与 CD 实现类在同一个包下。
package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class CDplayerConfig { }
注解 1 @Configuration 告知 Spring的应用上下文 要在该类中加载配置
注解 2 @ComponentScan 告知 Spring的应用上下文 要启用组件扫描,默认扫描与配置类相同的包
4、测试自动化装配 bean
package soundsystem; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = CDplayerConfig.class) public class CDPlayerTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); } }
- @RunWith 创建 Spring的应用上下文
- @ContextConfiguration 加载配置 --> 启用组件扫描 --> 扫描组件,发现带 @Component 注解的 CD实现类 --> 自动创建 bean
- @Autowired 将 CD实现类 对象 注入到测试代码中
5、自动装配 bean 的数量是不限的
public class CDPlayerTest { @Autowired private CompactDisc cd; @Autowired private CompactDisc cd2; @Autowired private CompactDisc cd3; @Autowired ......... @Autowired private CompactDisc cdn; @Test public void cdShouldNotBeNull() { assertNotNull(cd); assertNotNull(cd2); } }
标签:cdn ora framework sys layer ... 声明 创建 autowire
原文地址:http://www.cnblogs.com/xkxf/p/7140667.html