注入: 通过 spring 的配置文件,为成员变量赋值。
Set 注入: Spring 调用 set 方法,通过配置文件为成员变量赋值。
构造注入: Spring 调用构造方法,通过配置文件,为成员变量赋值。
构造方法 创建一个 person 类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package com.rhino;import lombok.Getter;public class Person { private Integer id; @Getter private String name; public Person (Integer id, String name) { this .id = id; this .name = name; } }
然后 applicationContext.xml 这样写
1 2 3 4 5 6 7 8 9 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id ="person" class ="com.rhino.Person" > <constructor-arg index ="0" value ="1" /> <constructor-arg index ="1" value ="小明" /> </bean > </beans >
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import com.rhino.Person;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestFunction { @Test public void test () { ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml" ); Person person = (Person) ctx.getBean("person" ); System.out.println(person.getName()); } }
构造方法重载
参数个数不同
通过 constructor-arg 数目进行区分
相同数目的参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.rhino; import lombok.Getter;public class Person { private Integer id; @Getter private String name; public Person (Integer id) { this .id = id; } public Person (String name) { this .name = name; } }
xml 文件进行这样写
1 2 3 4 5 6 7 8 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id ="person" class ="com.rhino.Person" > <constructor-arg index ="0" value ="小明" type ="java.lang.String" /> </bean > </beans >
使用 type 进行区分。