Spring(一)IOC容器

IOC容器

1、springioc容器可以帮我们新建对象,并给对象赋值。

org.lanqiao.entity.Student

public class Student {
	private int stuNo ; 
	private String stuName ; 
	private int stuAge ;
	public int getStuNo() {
		return stuNo;
	}
	public void setStuNo(int stuNo) {
		this.stuNo = stuNo;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public int getStuAge() {
		return stuAge;
	}
	public void setStuAge(int stuAge) {
		this.stuAge = stuAge;
	}
	
	@Override
	public String toString() {
		return this.stuNo+","+this.stuName+","+this.stuAge;
	}
	

applicationContext.xml

	<!-- 该文件中产生的所有对象,被spring放入了一个  称之为spring ioc容器的地方 -->
	<!-- id:唯一标识符    class:指定类型即类名和包名   -->
	<bean id="student" class="org.lanqiao.entity.Student">
		<!-- property:该class所代表的类的属性
			name:属性名
			value:属性值
		-->
		<property name="stuNo" value="2"></property>
		<property name="stuName" value="ls"></property>
		<property name="stuAge" value="24"></property>
	</bean>

Test.java

	public static void springIoc() {
        //创建容器
        ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
		//执行从springIOC容器中获取一个 id为student的对象
		Student student = (Student)conext.getBean("student") ;
    }

创建容器 new ClassPathXmlApplicationContext(“applicationContext.xml”) 时,

完成new对象和注入赋值两个操作。

2、IOC发展史

(1)手动new

Student student = new Student();
student.setXxx();

在这里插入图片描述

(2)简单工厂

在这里插入图片描述

(3)ioc (超级工厂)

IOC(控制反转)也可以称之为DI(依赖注入):
控制反转:将 创建对象、属性值 的方式 进行了翻转,从new、setXxx() 翻转为了 从springIOC容器getBean()
依赖注入:将属性值 注入给了属性,将属性 注入给了bean,将bean注入给了ioc容器;
无论要什么对象,都可以直接去springioc容器中获取,而不需要自己操作(new\setXxx())。

在这里插入图片描述

ioc分为2步:

a.先给springioc中存放对象并赋值

applicationContext.xml

	<bean id="javaCourse" class="org.lanqiao.newinstance.JavaCourse"></bean>
	<bean id="htmlCourse" class="org.lanqiao.newinstance.HtmlCourse"></bean>

b.拿

Test.java

	public static void learnCourseWithIoC() {
		ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
   		//获取student对象
		Student student = (Student)conext.getBean("student") ;
		student.learn("javaCourse");
	}
	
	public static void main(String[] args) {
		learnCourseWithIoC();
    }

Student.java

public class Student {
public void learn(String name) {	
		ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
    	//获取ICourse对象
		ICourse course = (ICourse)conext.getBean(name);	
		course.learn();	
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值