注:本系列博客是我学习《Spring in Action 4》的学习笔记,部分问题可能有雷同。如有侵权请私信指出,立马删除。
创建可以被发现的Bean
下面的代码创建了一个接口与一个接口实现,并为实现添加了一个@Component注解,告知Spring要为这个类创建Bean。
public interface CompactDisc {
void play();
}
@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);
}
}
启用组件扫描
@ComponentScan注解能够在Spring 中启用组件扫描,该注解默认扫描配置类相同包以及其子包,查找带有@Component注解的类,并且在Spring 中为其创建Bean.
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
如果我们的不想通过java注解的方式启用组件扫描,或者组件并不在@ComponentScan同包或者子包下面的话。可以使用xml文件来启用组件扫描。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="pub.zhouhui" />
</beans>
####测试
package pub.zhouhui;
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;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class CDPlayerTest {
@Autowired
private CompactDisc cd;
@Test
public void cdShouldNotBeNull() {
cd.play();
assertNotNull(cd);
}
}
@RunWith(SpringJUnit4ClassRunner.class)便于在测试开始的时候自动创建Spring的应用上下文。
@ContextConfiguration会告诉他需要在CDPlayerConfig中加载配置。
@Autowired将CompactDisc bean 注入到测试代码中