Spring基于xml的构造方法注入&setter注入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36146275/article/details/62888672

Spring的依赖注入分为:接口注入、构造方法注入、setter注入。

本篇博客实现后两种依赖注入方法——基于xml的构造方法注入与setter注入。

使用Spring框架需要使用5个依赖架包:beans、context、core、expression、logging


这里博主提供jar包的下载地址:【http://pan.baidu.com/s/1bpahZiB】


一、构造方法注入

此节需要用到三个类:User类,Test测试类,application.xml配置文件

User类:有id、name、age三个字段,并设置3个字段的setterAndGetter方法,并且创建带有id与name,name与age字段的构造方法

创建构造方法的快捷方式:在代码编辑框处右击→source→generate construct using fieds.在选择框中再选中需要的参数点击OK就创建好了。

项目结构如下:


1)User类:

/**
 * 构造方法注入:
 * 1、为字段生成setterAndGetter方法
 * 2、再为User构造两个方法,传参分别是【id、name】【name、age】
 * 3、右击→source→generate toString()方法,作测试用。toString()方法可以输出User类所有字段值
 * @author Administrator
 *
 */
public class User {

	private Integer id;
	private String name;
	private Integer age;

	public User(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public User(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	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 Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}
2)配置application.xml文件:

我们约定俗成把配置文件命名为application.xml,也有一些人会命名为beans.xml。

2.1)new一个application.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd">
	
</beans>

beans中的内容是我到spring官网copy过来的

【http://docs.spring.io/spring/docs/5.0.0.M5/spring-framework-reference/htmlsingle/#beans-factory-class】

打开网页后【ctrl+f】搜索【daos.xml】就可以copy了,copy过来会报错,因为缺少beans的结束标签</beans>,添加上就ok了


2.2)把User类配置给Spring管理

<bean>标签的class属性值要指定目标类,即需要给Spring管理的类。

class="全限定类名"

获取方法:


<?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="userId" class="com.demo.User">
		<constructor-arg index="0" type="java.lang.Integer" value="9527"></constructor-arg>	
		<constructor-arg index="1" type="java.lang.String" value="周星星"></constructor-arg>
	</bean>

</beans>
id:任意命名,要易于区分

class:要被spring管理的类,【class="包名.类名"】

<constructor-arg>标签:顾名思义就是"构造方法的参数"

index:构造方法参数所在位置的索引值

type:参数的类型

value:为参数赋值

到这里就完成了Spring管理User类的配置。

3)验证User类是否已经被Spring管理

new一个TestIOC测试类:@Test注解的意思是使用 JUnit 测试工具,具体的使用方法,这里不做细说

使用@Test 的原因是方便做测试,不用写main方法。

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

/**
 * 功能:
 * 测试Spring是否已经管理User类
 * @author Administrator
 *
 */
public class TestIoc {
	
	@Test
	public void demo01(){
		//spring工厂,加载xml配置文件
		String xmlPath = "com/demo/application.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//根据xml配置文件的设置,获取bean实例
		User user = (User) applicationContext.getBean("userId");
		System.out.println(user);
	}
}
xmlPath:右击application.xml文件→copy Qualified Name→删除【 项目名/src 】之后就是xml文件路径

userId:就是application.xml文件中配置<bean id="userId" >的值


输出结果:这就是Spring的控制反转,将创建实例的权利反转给Spring去管理,由它去创建实例。



二、setter注入

setter注入与构造方法注入都要配置XML文件,最大区别是配置的方式不同。

这里准备用Person类与Address类来演示setter注入,他们的关系如下:



1)创建Person类、Address类

Person类:为4个字段创建setterAndGetter方法,再创建一个toString()方法,用来输出字段的值。

它的值來自Spring的配置文件application.xml。

public class Person {
	
	private String name;
	private Integer age;
	private Address homeAddress;//家庭住址
	private Address companyAddress;//公司住址
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Address getHomeAddress() {
		return homeAddress;
	}
	public void setHomeAddress(Address homeAddress) {
		this.homeAddress = homeAddress;
	}
	public Address getCompanyAddress() {
		return companyAddress;
	}
	public void setCompanyAddress(Address companyAddress) {
		this.companyAddress = companyAddress;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", homeAddress=" + homeAddress + ", companyAddress="
				+ companyAddress + "]";
	}
}

Address:为addrsss、tel字段创建setterAndGetter方法,再创建一个toString()方法,

右击→source→generate toString()方法,作测试用。toString()方法可以输出User类所有字段值。

public class Address {
	
	private String address;//地址
	private String tel;//联系电话
	
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
	@Override
	public String toString() {
		return "Address [address=" + address + ", tel=" + tel + "]";
	}
}
2)配置application.xml文件:

构造方法注入使用的是<construct-arg>标签对字段进行赋值,而setter方法注入使用的是<property>标签对字段赋值。

注意:<property name=" ">,name的值必须与目标类(Person)的字段【一致】,否则程序运行会报"Error setting property values"的错误。

赋值有两种形式:

第一种:以name="" value="" 形式赋值,也叫普通值。<property name="name" value="郭靖">表示将目标类的"name"字段赋值为"郭靖"
第二种:以name="" ref="" 形式赋值,也叫引用值。<property name="homeAddress" ref="homeAddressId">表示将目标类的homeAddress字段赋值为"引用bean的值,bean的id=homeAddressId"
<?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">
		
	<!-- setter方法注入 --> 
<bean id="personId" class="com.demo1.Person">
 	<property name="name" value="郭靖"></property>
	<property name="age" value="18"></property>
	<property name="homeAddress" ref="homeAddressId"></property>
	<property name="companyAddress" ref="companyAddressId"></property> 
</bean>
<bean id="homeAddressId" class="com.demo1.Address">
	<property name="address" value="越秀区"></property>
	<property name="tel" value="123456"></property>
</bean>
<bean id="companyAddressId" class="com.demo1.Address">
	<property name="address" value="天河区"></property>
	<property name="tel" value="654321"></property>
</bean>

</beans>


3)创建测试类查看配置结果:

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

public class TestSetter {
	
	@Test
	public void test(){
		//加载Spring配置文件
		String xmlPath = "com/demo1/application.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		Person person = (Person) applicationContext.getBean("personId");//通过Spring获取Person的实例
		System.out.println(person);
	}
}

Person类以及Address类字段都已经有值

homeAddress跟companyAddress看起怪怪的,可以到Address类的toString()方法中删除Address:


这下好多了。


小结:构造方法注入与setter注入仅有一小点差异,最后都能达到同样的效果——控制反转(IOC),将new一个实例的权利反转给Spring去管理,让Spring通过配置文件去new一个实例。构造方法是使用<construct-arg index="" type="" value="">标签进行注入,setter是使用<property name="" value="">标签进行注入,两者都是基于xml配置文件进行操作。还有一种方法是基于注解注入,可以替代基于xml的繁琐配置过程。





猜你喜欢

转载自blog.csdn.net/weixin_36146275/article/details/62888672