案例要求:创建一个 Studentservice 类,其中需要使用 studentDao 接口的保存方法,来存储一个Student 类的对象,StudentDao 接口有两个不同的实现类,通过 Spring 的方式,为 Student类创建对象并为属性赋值,并通过 Spring 的方式,创建 Studentservice 类的对象以及StudentDao 接口的一个实现类对象,通过依赖注入的方式模拟完成保存的操作。
1、配置依赖
在pom.xml中配置依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
2、创建applicationContext.xml文件,并且点击File->Project...->找到Spring,点击+,选中文件导入
<?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">
<bean id="student" class="cn.clz.pojo.Student">
<property name="name" value="海绵宝宝"></property>
<property name="age" value="18"></property>
</bean>
<bean id="studentDao1" class="cn.clz.dao.impl.StudentDaoImpl1"></bean>
<bean id="studentDao2" class="cn.clz.dao.impl.StudentDaoImpl2"></bean>
<bean id="studentService" class="cn.clz.service.StudentService">
<property name="studentDao" ref="studentDao1"></property>
</bean>
</beans>
3、创建实体类Student、接口StudentDao、接口实现类StudentDaoImpl1和实现类StudentDaoImpl2、类StudentService
Student.java
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
StudentDao.java
public interface StudentDao {
void save();
}
StudentDaoImpl1.java
public class StudentDaoImpl1 implements StudentDao {
public void save() {
System.out.println("实现类1实现StudentDao的save方法...");
}
}
StudentDaoImpl1.java
public class StudentDaoImpl2 implements StudentDao {
public void save() {
System.out.println("实现类2实现StudentDao的save方法...");
}
}
StudentService.java
public class StudentService {
private StudentDao studentDao;
public void save(){
studentDao.save();
}
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
4、编写测试TestStudent.java
public class TestStudent {
public static void main(String[] args) {
//加载spring容器
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) ctx.getBean("student");
StudentService studentService = (StudentService) ctx.getBean("studentService");
System.out.println(student);
studentService.save();
}
}
5、运行结果