通过 Spring 工厂以及配置文件,为所创建对象的成员变量赋值。
前置条件
1 2 3 4 5 <dependency > <groupId > org.springframework</groupId > <artifactId > spring-context</artifactId > <version > 5.1.4.RELEASE</version > </dependency >
相关类和文件 Person 创建一个 Person 类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.rhino; public class Person { private Integer id; private String name; public Integer getId () { return id; } public void setId (Integer id) { this .id = id; } public String getName () { return name; } public void setName (String name) { this .name = name; } public Person () { System.out.println ("Person.person" ); } }
applicationContext.xml 1 2 3 4 5 6 7 <?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" /> <bean id ="user" class ="com.rhino.User" /> </beans >
直接赋值 通过编码的方式,为成员变量进行赋值,存在耦合。
1 2 3 4 5 6 7 8 @Test public void test () { ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml" ); Person person = (Person) ctx.getBean("person" ); person.setId(1 ); person.setName("123" ); }
如何进行注入
类层面上,要为成员变量进行 set、get 方法
配置 spring 的配置文件
修改 applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?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" > <property name ="id" > <value > 10</value > </property > <property name ="name" > <value > 小明</value > </property > </bean > <bean id ="user" class ="com.rhino.User" /> </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()); } }
输出