1.创建一个新的命名为lesson2,将lesson中的文件拷贝到lesson2中。
2.在SlayDragonQuest中添加组件注解符
3.在RescueDamselQuest中添加
4.修改BravekNight
@Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false
5.修改
spring项目无法引用@Resource注解
解决办法:Spring项目中缺少javax.annotation包的依赖。在maven配置文件pom.xml中加入依赖。
<!-- Javax Annotation -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
6.创建配置文件
<?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.jyq.spring.lesson2" />
</beans>
7.创建测试类
package net.jyq.spring.lesson2;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Testknight {
private ClassPathXmlApplicationContext context;
@Before
public void init() {
// 基于Spring配置文件创建应用容器
context = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
// 提示用户
System.out.println("Spring应用容器已创建。");
}
@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();
// 提示用户
System.out.println("Spring应用容器已关闭。");
}
}
运行结果
9.面向接口
9.1在lesson2中创建两个接口
9.2修改
9.3修改测试类
运行结果