Spring(三)依赖注入(DI)

Spring学习笔记(三)

一、什么是依赖注入:

  IOC(控制反转)也称为DI(依赖注入),简单来说就是指将SpringIoc里面的资源注入到对象中。

二、编写简单程序了解依赖注入:

1.导入相应的spring的jar包:

在这里插入图片描述

2.创建实体类:

1.实体类:person.java

package entity;

public class Person {
    
    
		private String name;
		private int 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;
		}
		
}

2.实体类course.java

package entity;

public class Course {
    
    
	private String courseName;
	private int courseHours;
	private Person person;
	public String getCourseName() {
    
    
		return courseName;
	}
	public void setCourseName(String courseName) {
    
    
		this.courseName = courseName;
	}
	public int getCourseHours() {
    
    
		return courseHours;
	}
	public void setCourseHours(int courseHours) {
    
    
		this.courseHours = courseHours;
	}
	public Teacher getTeacher() {
    
    
		return person;
	}
	public void setTeacher(Person person) {
    
    
		this.person = person;
	}
	
	public void showInfo() {
    
    
		System.out.println("课程:"+courseName+"  上课时间: "+courseHours+"  学者: "+person.getName());
	}
}

3.编写Spring配置文件applicationContext:

<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
					http://www.springframework.org/schema/beans/spring-beans.xsd">						
	
<!-- 依赖注入 -->
<bean id="person" class="entity.Person">
	<property name="name" value="李帅"></property>
	<property name="age" value="29"></property>
</bean>	

	
<bean id="course" class="entity.Course">
	<property name="courseName" value="Java"></property>
	<property name="courseHours" value="64"></property>
	<property name="person" ref="person"></property>
</bean>	


</beans>

4.编写测试类:

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import entity.Course;


public class Test2 {
    
    
	public static void main(String [] agrs) {
    
    
		 //创建spring 的IOC容器对象
		 ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
		 //直接从SpringIoc容器中,根据id值获取属性值已经赋值完毕的对象
		 Course course=(Course)context.getBean("course");
		 course.showInfo();
	 }
}

5.总结

运行结果:
在这里插入图片描述
从这个程序我们可以得到:SpringIoc容器分别用两种放松对对象的属性赋值,而这就就可以简单理解为依赖注入,让这两个类产生了依赖关系。

猜你喜欢

转载自blog.csdn.net/qq_46046423/article/details/114602989