文章目录
一、打开上一讲的项目
二、利用注解配置类取代Spring配置文件
1、在net.hw.spring包里创建lesson03子包
2、拷贝lesson02的类和接口到lesson03中
3、在lesson03中创建Spring配置类来取代Spring配置文件
注解:@Configuration声明当前类是一个配置类,对应一个Spring配置文件,可以取而代之。
注解:@ComponentScan自动扫描包名下所有使用@Service、@Component、@Repository、@Controller的类,并注册为Bean。
注解:@ComponentScan(“net.hw.spring.lesson03”)相当于配置文件里的<context:component-scan base-package=“net.hw.spring.lesson03”/>。
4、在yc.net.spring中创建lesson包
5、创建测试类 - TestKnight
package net.yc.spring.lesson03;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 功能:测试骑士类
*/
public class TestKnight {
private AnnotationConfigApplicationContext context;
@Before
public void init() {
// 基于Spring配置类创建应用容器
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
public void testBraveKnight() {
// 根据名称从应用容器里获取勇敢骑士对象
BraveKnight braveKnight = (BraveKnight) context.getBean("mike");
// 勇敢骑士执行任务
braveKnight.embarkOnQuest();
}
@Test
public void testDamselRescuingKnight() {
// 根据名称从应用容器里获取拯救少女骑士对象
DamselRescuingKnight damselRescuingKnight = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
// 拯救少女骑士执行任务
damselRescuingKnight.embarkOnQuest();
}
@After
public void destroy() {
// 关闭应用容器
context.close();
}
}