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容器分别用两种放松对对象的属性赋值,而这就就可以简单理解为依赖注入,让这两个类产生了依赖关系。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值