In the last lecture, we used annotations to streamline the XML configuration file. In this lecture, we plan to replace the XML configuration file with annotation configuration classes.
1. Use the annotation configuration class to replace the Spring configuration file
1. Create a lesson03 sub-package in the net.tjl.spring package
2. Create a Spring configuration class to replace the Spring configuration file
package net.tjl.spring.lesson03;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("net.tjl.spring.lesson03") //组件扫描表
public class AnnotationConfig {
}
3. Create a test class-TestKnight
package net.tjl.spring.lesson03;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 功能:测试骑士类
* 作者:谭金兰
* 日期:2021年03月17日
*/
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();
}
}
* Run the test class and view the results