一、利用注解配置类取代Spring配置文件
(一)打开项目
- Maven项目 - SpringDemo
(二)创建新包
- 在
net.huawei.spring
包创建day03
子包
(三)拷贝类与接口
(四)创建注解配置类
package net.huawei.spring.day03;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("net.huawei.spring.day03")
public class SpringConfig {
}
- 注解@Configuration声明当前类是一个配置类,对应一个Spring配置文件,可以取而代之。
- 注解@ComponentScan自动扫描包名下所有使用@Component、@Service、@Repository、@Mapper、@Controller的类,并注册为Bean。
- 注解@ComponentScan(“net.huawei.spring.day03”)相当于Spring配置文件里的<context:component-scan
base-package=“net.huawei.spring.day03”/>。
(五)创建测试类
- 在test/java里创建net.huawei.spring.day03包,在包里创建TestKnight类
package net.huawei.spring.day03;
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(SpringConfig.class);
}
@Test
public void testKnight() {
Knight knight1 = (Knight) context.getBean("RobinHood");
knight1.embarkOnQuest();
Knight knight2 = (Knight) context.getBean("rescueDamselKnight");
knight2.embarkOnQuest();
}
@After
public void destroy() {
context.close();
}
}
(六)运行测试类