How to inject value into bean properties in Spring

本文介绍了在Spring中注入Bean属性的三种方法:正常方式、快捷方式和使用p schema的方式。通过一个简单的Java类,展示了如何使用Spring配置文件进行属性注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In Spring, there are three ways to inject value into bean properties.

  • Normal way
  • Shortcut
  • “p” schema

See a simple Java class, which contains two properties – name and type. Later you will use Spring to inject value into the bean properties.

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. Normal way

Inject value within a ‘value’ tag and enclosed with ‘property’ tag.

<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. Shortcut

Inject value with “value” attribute.

<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” schema

Inject value by using “p” schema as an attributes.

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

Remember declares the xmlns:p=”http://www.springframework.org/schema/p in the Spring XML bean configuration file.

Conclusion

Which methods to use is totally base on personal preference, it will not affect the value inject into the bean properties.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值