前回の講義では、注釈を使用してXML構成ファイルを合理化しました。この講義では、XML構成ファイルを注釈構成クラスに置き換える予定です。
1.アノテーション構成クラスを使用してSpring構成ファイルを置き換え
ます1.net.tjl.springパッケージにlesson03サブパッケージを
作成します2.Spring構成クラスを作成してSpring構成ファイルを置き換えます
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.テストクラスを作成します-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();
}
}
*テストクラスを実行して結果を表示する