Spring IOC之属性注入

1.项目创建

https://blog.csdn.net/zhaolinxuan1/article/details/84897949

https://blog.csdn.net/zhaolinxuan1/article/details/84932897

2.UserInfo类

public class UserInfo {
	private String name;
	private Integer age;
	private DepartMent departMent;
	public UserInfo(){}

	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 DepartMent getDepartMent() {
		return departMent;
	}



	public void setDepartMent(DepartMent departMent) {
		this.departMent = departMent;
	}



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

	
	
}
 

DepartMent类:

public class DepartMent {
	private Integer deId;

	private String deName;

	public Integer getDeId() {
		return deId;
	}
	public DepartMent(){}

	public void setDeId(Integer deId) {
		this.deId = deId;
	}

	public String getDeName() {
		return deName;
	}

	public void setDeName(String deName) {
		this.deName = deName;
	}

	@Override
	public String toString() {
		return "DepartMent [deId=" + deId + ", deName=" + deName + "]";
	}

}

3.beans.xml

在xml中创建

 <bean id="departMent" class="com.DepartMent"> 
    <property name="deId" value="101"/>  
    <property name="deName" value="技术部"/> 
  </bean>  

使用<property name="departMent" ref="departMent"/> 注入userInfo 的bean中

<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">  
  <bean id="departMent" class="com.DepartMent"> 
    <property name="deId" value="101"/>  
    <property name="deName" value="技术部"/> 
  </bean>  
  <!-- 依赖注入 -->  
  <bean id="userInfo" class="com.UserInfo" scope="singleton"> 
    <property name="name" value="zlx"/>  
    <property name="age" value="29"/>  
    <property name="departMent" ref="departMent"/> 
  </bean> 
</beans>

4.测试

public class Test {

	public static void main(String[] args) {
		
		ConfigurableApplicationContext bf = new ClassPathXmlApplicationContext("beans.xml");
		UserInfo userInfo = (UserInfo) bf.getBean("userInfo");
		System.out.println(userInfo);
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值