秦悦明的运维笔记

Spring-组件扫描

spring会自动发现应用上下文中所创建的bean。

创建一个CDPleaer类,让Spring发现它,并将CompactDisc bean注入进来。

SgtPeppers.java
主要是用@Component注解,表明该类会作为一个组件类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package soundsystem;
import org.springframework.stereotype.Component;
@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);
}
}

不过组件扫描默认是不启用的,得配置一下Spring,让他去寻找带有@Component的组件,如下:
CDPlayerConfig.java

1
2
3
4
5
6
7
8
package soundsystem;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class CDPlayerConfig {
}

然后通过CDPlayerTest.java类来测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package soundsystem;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
BUILD SUCCESSFUL
Total time: 16.894 secs

gradle测试通过,说明SgtPeppers被很好的创建出来了,不为空。