在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/