1.新建AnnotationConfig.java文件取代配置文件
package net.ty.spring.lesson03;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
@Configurable
@ComponentScan("net.ty.spring.lesson03")
public class AnnotationConfig {
}
测试
package net.ty.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() {
// 基于注解配置类创建应用容器
context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
}
@Test
public void testBraveKnight() {
// 根据名称从应用容器里获取勇敢骑士对象
BraveKnight knight = (BraveKnight) context.getBean("Mike");
// 勇敢骑士执行任务
knight.embarkOnQuest();
}
@Test
public void testDamselRescuingKnight() {
// 根据名称从应用容器里获取救美骑士对象
DamselRescuingKnight knight = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
// 救美骑士执行任务
knight.embarkOnQuest();
}
@After
public void destroy() {
// 关闭应用容器
context.close();
}
}
![]()