电子商务网站建设特点微营销平台有哪些
文章目录
- 一、利用注解配置类取代Spring配置文件
- (一)打开项目
- (二)创建新包
- (三)拷贝类与接口
- (四)创建注解配置类
- (五)创建测试类
- (六)运行测试类
利用注解配置类取代XML配置文件。
一、利用注解配置类取代Spring配置文件
(一)打开项目
- Maven项目 - SpringDemo
(二)创建新包
- 在net.huawei.spring包创建day03子包
(三)拷贝类与接口
- 将
day02
子包的类与接口拷贝到day03
子包
(四)创建注解配置类
- 在
day03
子包里创建SpringConfig
类,取代Spring配置文件
package net.huawei.spring.day03;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;/*** 功能:注解配置类*/
@Configuration // 表明是Spring配置类
@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
类
AnnotationConfigApplicationContext ⟹ \Longrightarrow⟹ApplicationContext⟹ \Longrightarrow⟹BeanFactory
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; // 基于注解配置类的应用容器@Beforepublic void init() {// 基于注解配置类创建应用容器context = new AnnotationConfigApplicationContext(SpringConfig.class);}@Testpublic void testKnight() {// 根据名称从应用容器里获取勇敢骑士对象Knight knight1 = (Knight) context.getBean("RobinHood");// 勇敢骑士执行任务knight1.embarkOnQuest();// 根据名称从应用容器里获取救美骑士对象Knight knight2 = (Knight) context.getBean("rescueDamselKnight");// 救美骑士执行任务knight2.embarkOnQuest();}@Afterpublic void destroy() {// 关闭应用容器context.close();}
}
(六)运行测试类
- 运行
testKnight
测试方法,查看结果