Java 用弹簧注入字符串的快捷方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18596235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:20:58  来源:igfitidea点击:

shortcut for injecting strings with spring

javaspring

提问by naumcho

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

我通过执行以下操作在我的 spring 配置中注入字符串:

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

Is there a shorter way of doing it?

有没有更短的方法?

Update:I am using spring 3.0.3.

更新:我使用的是 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>
            ...

Seems like this works:

看起来像这样:

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

但我同意这最终应该进入财产并被传递的建议。

采纳答案by Sotirios Delimanolis

You should not have Stringbeans. Just use their value directly.

你不应该吃String豆子。直接使用它们的值即可。

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

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

strings.key=Region

Declare a PropertyPlaceholderConfigurer

声明一个 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 will inject the value from the strings.propertiesfile into this keyString.

Spring 会将strings.properties文件中的值注入到这个keyString 中。

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

这显然假定@Value注解出现的类是在与PropertyPlaceholderConfigurer.

回答by Aaron Digulla

There is no need to create a bean of type String. Just pass the value to constructor-arg:

无需创建类型为 的 bean String。只需将值传递给constructor-arg

<bean id="foo" class="x.y.Foo">
    <constructor-arg value="Region"/>
</bean>

works.

作品。

回答by ikumen

In addition to the other answers and if you're using Spring 3.1+, you can use the constructor namespace.

除了其他答案之外,如果您使用的是 Spring 3.1+,则可以使用构造函数命名空间。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:c="http://www.springframework.org/schema/c" <-- add c namespace
  ...

<bean id="someClass" class="a.b.c.SomeClass"
  c:someProperty="Region"
/>