Sping之Ioc

时间:2023-12-16 19:55:38

Ioc,控制反转,依赖注入!

作用:降低代码之间的耦合性

代码永远是最好的示例:

1.新建test类

package demo;

public class test {
	String string_var;
	int int_var;
	char char_var;
	double double_var;

	public String getString_var() {
		return string_var;
	}

	public void setString_var(String string_var) {
		this.string_var = string_var;
	}

	public int getInt_var() {
		return int_var;
	}

	public void setInt_var(int int_var) {
		this.int_var = int_var;
	}

	public char getChar_var() {
		return char_var;
	}

	public void setChar_var(char char_var) {
		this.char_var = char_var;
	}

	public double getDouble_var() {
		return double_var;
	}

	public void setDouble_var(double double_var) {
		this.double_var = double_var;
	}

	public void inin(){
		System.out.println("在init()方法中String的值是:"+string_var);
		System.out.println("在init()方法中int的值是:"+int_var);
		System.out.println("在init()方法中char的值是:"+char_var);
		System.out.println("在init()方法中double的值是:"+double_var);
	}

	public void printAll(){
		System.out.println("在printAll()方法中String的值是:"+string_var);
		System.out.println("在printAll()方法中int的值是:"+int_var);
		System.out.println("在printAll()方法中char的值是:"+char_var);
		System.out.println("在printAll()方法中double的值是:"+double_var);
	}
}

2.新建applicationContext.xml配置文件<?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-3.1.xsd">
	<!-- init-method属性:在取得Bean实例并对属性进行注入以后自动执行的,
		 可解决注入后对属性值进行继续更改的操作;唯一id名,class为类的路径 -->
	<bean id="test_ref" class="demo.test" init-method="inin">
          <!-- 对类里的字段进行注入值 --> <property name="string_var" value="高渐离"></property> <property name="int_var" value="66"></property> <property name="char_var" value="女"></property> <property name="double_var" value="66.66"></property> </bean>
<bean id="runit_ref" class="demo.runit">
          <!-- ref引用test_ref --> <property name="test_ref" ref="test_ref"></property> </bean> </beans>

3.新建runit类,方便测试,直接写了main方法

package demo;

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

public class runit {
    test test_ref;

    public test getTest_ref() {
        return test_ref;
    }

    public void setTest_ref(test test_ref) {
        this.test_ref = test_ref;
    }
    public static void main (String[] args){
        ApplicationContext contex = new ClassPathXmlApplicationContext("applicationContext.xml");
        runit runit_ref = (runit) contex.getBean("runit_ref");
        runit_ref.getTest_ref().printAll();
    }
}

  以上示例只展示了基本数据类型的注入,还有构造方法、Properties文件等注入方法!自己查去吧!