一、利用组件注解符精简Spring配置文件
1、创建net.lh.spring.lesson02包
2、将lesson01子包中的四个类拷贝到;lesson02中
3、修改杀龙任务类-SlayDragonQuest
如果没有设置参数那么组件采用默认名称
4、修改救美任务类 - RescueDamselQuest
5、修改勇敢骑士类 - BraveKnight
注意:删除setSlayDragonQuest()方法,因为已经通过自动装配注解设置了勇敢骑士的杀龙任务属性。
6、修改救美骑士类 - DamselRescuingKnight
注意:删除了构造方法,因为已经通过资源注解符将救美任务属性注入了救美骑士组件。
7、创建Spring配置文件
组件扫描:扫描指定包下添加了注解符的类(@Component、@Service、@Repository、@Mapper、@Controller),将其生成Bean对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--组件扫描,扫描指定包下添加了注解符的类或接口,将其生成Bean对象-->
<context:component-scan base-package="net.lh.spring.lesson02" />
</beans>
8、创建测试类 - TestKnight
package net.lh.spring.lesson02;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestKnight {
private ClassPathXmlApplicationContext context; // 基于类路径XML配置文件的应用容器
@Before
public void init() {
// 基于Spring配置文件创建应用容器
context = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
}
@Test
public void testKnight() {
// 根据名称从应用容器里获取勇敢骑士对象
BreakKnight knight1 = (BreakKnight) context.getBean("Mike");
// 勇敢骑士执行任务
knight1.embarkOnQuest();
// 根据名称从应用容器里获取救美骑士对象
DamselRescuingKnight knight2 = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
// 救美骑士执行任务
knight2.embarkOnQuest();
}
@Test
public void testDamselRescuingKnight(){
}
@After
public void destroy() {
// 关闭应用容器
context.close();
}
}
运行测试方法testKnight(),查看结果
二、程序优化 - 面向接口
Spring框架可以方便地管理Bean及其相互依赖。为了模块之间实现松耦合,一般采用面向接口的方式。多种骑士,多种任务,可以任意搭配。为了实现这个效果,我们应该抽象出两个接口:骑士接口(Knight)和任务接口(Quest)。骑士接口有两个实现类:BraveKnight和DamselRescuingKnight;任务接口有两个实现类:SlayDragonQuest和RescueDamselQuest。
1、创建任务接口 - Quest
package net.lh.spring.lesson02;
public interface Quest {
void embark();
}
2、创建骑士接口 - Knight
package net.lh.spring.lesson02;
public interface Knight {
void embarkOnQuest();
}
3、修改杀龙任务类 - SlayDragonQuest(让杀龙任务类实现任务接口)
4、修改救美任务类 - RescueDamselQuest(让救美任务类实现任务接口)
5、修改勇敢骑士类 - BraveKnight(让勇敢骑士类实现骑士接口)
注意:SlayDragonQuest类改成了Quest接口,这样就可以给该骑士自动装配任何任务(实现了Quest接口的Bean),增加了程序的灵活性。