`
默翁1
  • 浏览: 25220 次
社区版块
存档分类
最新评论

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics