一、实验目的
1、掌握Spring项目工程搭建
2、掌握Spring核心配置文件基本配置流程
3、掌握两种注入方式
二、实验任务
1、创建项目并实现Spring两种注入方式(setter注入and构造器注入),并分析两者区别。
这两种方法的不同主要就是在 xml 文件下对应使用 property 和 constructor-arg
setter注入:Spring调用一个对象的 set 方法注入前,而且这个对象必须先被实例化
构造器注入:Spring会在调用构造函数前,实例化好构造函数需要的依赖对象,然后把这些经过实例化后的对象作为参数去调用构造函数
三、实验内容与要求
1、搭建项目环境
2、创建教师的业务层和持久化层
3、创建一个根据名字删除教师的方法
4、通过ApplicationContext初始化Spring容器并调用删除方法
5、分别编写两种注入方式进行测试
四、程序设计
截图,代码,关键步骤,结果验证
项目环境概况
持久层
package com.shiyan.spring.dao;
public interface TeacherDao {
void delete(); //删除
}
package com.shiyan.spring.dao;
import org.springframework.stereotype.Repository;
@Repository
public class TeacherImpl implements TeacherDao{
@Override
public void delete() {
System.out.println("delete a teacher"); //打印目标文字
}
}
业务层
//setter方法注入
@Service
public class TeacherService {
private TeacherDao teacherDao;
public void setTeacherDao(TeacherDao teacherDao) {
this.teacherDao = teacherDao;
}
public void run(){
System.out.println("Set方法delete:");
teacherDao.delete();
}
}
//构造器注入
@Service
public class TeacherService2 {
private TeacherDao teacherDao;
public TeacherService2(TeacherDao teacherDao) {
this.teacherDao = teacherDao;
}
public void run(){
System.out.println("构造delete:");
teacherDao.delete();
}
}
测试方法
public class test { //测试类
@Test
public void testTeacherset(){
ApplicationContext context = new ClassPathXmlApplicationContext("beanter.xml");
TeacherService teacherService = context.getBean("service", TeacherService.class);
teacherService.run();
}
@Test
public void testTeachercre(){
ApplicationContext context = new ClassPathXmlApplicationContext("beanter.xml");
TeacherService2 service2 = context.getBean("service2", TeacherService2.class);
service2.run();
}
}
注入方法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
//setter注入
<bean class="com.shiyan.spring.service.TeacherService" id="service">
<property name="teacherDao" ref="teacherimpl"></property>
</bean>
<bean class="com.shiyan.spring.dao.TeacherImpl" id="teacherimpl"></bean>
//构造器注入
<bean class="com.shiyan.spring.service.TeacherService2" id="service2">
<constructor-arg index="0" ref="teacherimpl"></constructor-arg>
</bean>
</beans>
运行结果
五、实验总结
通过本次实验,我较为熟练地掌握了Spring项目工程的搭建,对Spring核心配置文件基本配置流程较为熟悉,掌握了两种注入方式,能够实现Spring两种注入方式(setter注入and构造器注入),并对它们间的区别有所了解。