如何在Spring中将值注入bean属性

在Spring中,可以通过三种方式将值注入到bean属性中。

  • 正常方式
  • 捷径
  • “ p”模式

查看一个简单的Java类,其中包含两个属性-名称和类型。 稍后,您将使用Spring将值注入到bean属性中。

package com.mkyong.common;

public class FileNameGenerator 
{
	private String name;
	private String type;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}

1.正常方式

将值插入“值”标签内,并用“属性”标签括起来。

<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-2.5.xsd">

	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
		<property name="name">
			<value>mkyong</value>
		</property>
		<property name="type">
			<value>txt</value>
		</property>
	</bean>
</beans>

2.捷径

使用“值”属性注入值。

<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-2.5.xsd">

	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator">
		<property name="name" value="mkyong" />
		<property name="type" value="txt" />
	</bean>
	
</beans>

3.“ p”模式

通过使用“ p”模式作为属性来注入值。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator" 
             p:name="mkyong" p:type="txt" />
	
</beans>

切记在Spring XML bean配置文件中声明xmlns:p =“” http://www.springframework.org/schema/p

结论

使用哪种方法完全基于个人喜好,它不会影响注入到bean属性中的值。

翻译自: https://mkyong.com/spring/how-to-define-bean-properties-in-spring/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值