spring的属性注入方法

public class Person {
	//儿子,该属性是son类的一个实例
	private Son son;
	private String age;
	public Son getSon() {
		return son;
	}
	public void setSon(Son son) {
		this.son = son;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}

 

public class Son {
	private String age;

	public String getAge() {
		return age;
	}

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

 

<bean id="person" class="application.Person">
		<property name="age" value="20"></property>
		<!-- 该属性是Son类的一个实例 -->
		<property name="son">
			<bean class="application.Son">
				<property name="age" value="16"></property>
			</bean>
		</property>
	</bean>

 

public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("config/applicationContext.xml");
		Person person=(Person)context.getBean("person");
		System.out.println("person的年龄为:"+person.getAge());
		System.out.println("person的son的年龄为:"+person.getSon().getAge());
		
	}

 

person的年龄为:20
person的son的年龄为:16

 配置方式二:通过PropertyPathFactoryBean类,可以注入某个实例的属性值

<bean id="son1" class="application.Son">
		<!-- 将person类中son的age属性输入到son1中age属性 -->
		<property name="age">
			<bean id="person.son.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
		</property>
	</bean>

 

public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("config/applicationContext.xml");
		Son son1=(Son)context.getBean("son1");
		System.out.println(son1.getAge());
	}



结果为:16

 配置方式三:使用PropertyPathFactoryBean必须指定以下两个属性。
                       1.targetBeanName:用于指定目标bean,确定获取哪个bean的属性值。
                        2.propertyPath:用于指定属性,确定获取目标bean的哪个属性值,此处的属性可直接使用  属性表达式。可以将基本数据类型的属性值定义成bean实例。

<bean id="son2" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
		<property name="targetBeanName">
			<value>person</value>
		</property>
		<property name="propertyPath">
			<value>son</value>
		</property>
	</bean>

 

public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("config/applicationContext.xml");
		Son son2=(Son)context.getBean("son2");
		System.out.println(son2.getAge());
	}


结果:16

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值