Spring设置注入和构造注入

在Spring中注入方式有设置注入和构造注入。设置注入就是指要被注入的类中定义有一个setter()方法,并在参数中定义需要注入的对象。简单的看个例子。

定义有User类,并覆写了toString()方法。

package com.zcl.spring.setterinjection;

public class User {
	private String name ;
	private int age ;
	private String country ;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String toString(){
		return name + " is " + age + " years old,living in " + country ; 
	}
}
配置beans.xml文件,通过设置注入为类中属性注入值

<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"> 
	<bean id="user" class="com.zcl.spring.setterinjection.User">
		<property name="name" value="Zhao" />
		<property name="age" value="22" />
		<property name="country" value="China" />
	</bean>
</beans>

测试一下:

package com.zcl.spring.setterinjection;

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

public class Main {
	public static void main(String args[]){
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ;
		User user = (User)context.getBean("user") ;
		System.out.println(user) ;
	}
}

输入结果:

Zhao is 22 years old,living in China

现在我们来看写构造注入,所谓构造注入就是指要被注入的类中声明一个构造方法,并在此方法的参数中定义要注入的对象。修改下刚刚的User类。

package com.zcl.spring.setterinjection;

public class User {
	private String name ;
	private int age ;
	private String country ;
	
	public User(String name, int age, String country) {
		this.name = name;
		this.age = age;
		this.country = country;
	}

	public String toString(){
		return name + " is " + age + " years old,living in " + country ; 
	}
}

配置beans.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"> 
	<bean id="user" class="com.zcl.spring.setterinjection.User">
		<constructor-arg value="Zhao" />
		<constructor-arg value="22" />
		<constructor-arg value="China" />
	</bean>
</beans>

测试函数一样,打印结果也一样。




  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值