关于Spring-IOC容器的使用介绍

学习ioc容器之前,我首先需要按照教程操作练习,切勿死扣概念,概念过于抽象复杂

下面我结合自己的一个小例子给大家介绍下ioc容器的使用方法

第一步:创建web项目,导入spring所需要的jar包关于Spring-IOC容器的使用介绍_第1张图片

第二步:配置applicationContext.xml文件,并创建标签配置属性参数



       
  
       
     
      
  
  
  
     
     
     
     
  

第三步:创建一个学生类 并且声明属性  name  age  school   然后set三个属性,创建一个方法打印属性

package com;

public class Student {
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
	}
	String name;
	int age;
	String school;
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void setSchool(String school) {
		this.school = school;
	}
	public void method() {
		System.out.println("姓名:"+name+"  年龄:"+age+"  学校:"+school);
	}

}

第四步:再创建一个老师类  并且声明属性  name  sex  然后set两个属性,在老师类中声明学生类的实例student,创建一个方法打印属性

package com;

public class Teacher {
	String name;
	String sex;
	
	Student student;
	public void setStu(Student student) {
		this.student = student;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	public void methodinfo() {
		System.out.println(student.toString()+"  指导老师:"+name+"  老师性别:"+sex);
	}
	

}

第五步:创建main方法  调用方法老师类中的方法打印老师类和学生的属性

package com;

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

public class Test {

	public static void main(String[] args) {
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		     /*Student s=(Student)ac.getBean("stu");
		     s.method();*/
		     
		     Teacher t=(Teacher) ac.getBean("tea");
		     t.methodinfo();

	}

}
关于Spring-IOC容器的使用介绍_第2张图片

综上所述可以看出ioc的作用:   就是在一个类中可以不用new对象就可以获得另外一个类的实例,也就是说spring容器负责自动创建所需要类的实例了,以前我们都还是new一个所需要的类,依靠ioc效率大大提高,降低了代码的耦合度。


你可能感兴趣的:(spirng,IOC,spring)