用弹簧注入字符串的快捷方式 [英] shortcut for injecting strings with spring

查看:70
本文介绍了用弹簧注入字符串的快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过执行以下操作在Spring配置中注入了Strings:

I inject Strings in my spring config by doing the following:

<bean class="java.lang.String">
    <constructor-arg type="java.lang.String" value="Region" />
</bean>

有更短的方法吗?

更新:
我使用的是Spring 3.0.3。

Update: I am using spring 3.0.3.

这些实际上用于填充列表:

These are actually used to populate a list:

        <list>
            <bean class="java.lang.String">
                <constructor-arg type="java.lang.String" value="Region" />
            </bean>
            ...

看起来像是这样的:

<list>
   <value>Region</value>
   <value>Name</value>
   ....

但我同意这个建议最终会在属性并被传入。

But I agree with the suggestions that this should eventually go in a property and be passed in.

推荐答案

你不应该有字符串 bean 。只需直接使用它们的值。

You should not have String beans. Just use their value directly.

创建属性文件 strings.properties 并将其放在类路径上

Create a properties file strings.properties and put it on the classpath

strings.key=Region

声明 PropertyPlaceholderConfigurer

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>strings.properties</value>
    </property>
</bean>

然后注释实例字段字符串为

Then annotate instance field Strings as

@Value("${strings.key}")
private String key;

Spring将从 strings.properties 将文件放入此字符串。

Spring will inject the value from the strings.properties file into this key String.

这显然假定 @Value 注释出现的是在与 PropertyPlaceholderConfigurer 相同的上下文中管理的bean。

This obviously assumes that the class in which the @Value annotation appears is a bean managed in the same context as the PropertyPlaceholderConfigurer.

这篇关于用弹簧注入字符串的快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆