java 如何在 spring 中定义非强制属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11773122/
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-10-31 06:19:02  来源:igfitidea点击:

how to define not mandatory property in spring?

javaspring

提问by Julias

I'm using spring 3 with PropertyPlaceholderConfigurator.

我将 spring 3 与 PropertyPlaceholderConfigurator 一起使用。

My properties code looks like as following:

我的属性代码如下所示:

@Configuration
public class MyProps {

    @Value("${prop1}")
    public String prop1;

    ...
}

If I do not have a prop1 in my .properties file the spring fails to initialize it's context.

如果我的 .properties 文件中没有 prop1,则 spring 无法初始化它的上下文。

The question is how can I define that this property is not mandatory? some annotation, configuration?

问题是我如何定义这个属性不是强制性的?一些注释,配置?

回答by tibtof

You could use a default value:

您可以使用默认值:

@Value("${prop1:}")
public String prop1;

and spring will inject an empty string if the property isn't defined. The syntax is ${property:defaultValue}.

如果未定义属性,则 spring 将注入一个空字符串。语法是${property:defaultValue}.

回答by adamoldak

I'm not sure if it is possible to make a single property optional but surely you can force the property placeholder to ignore unresolved properties:

我不确定是否可以将单个属性设为可选,但您肯定可以强制属性占位符忽略未解析的属性:

<context:property-placeholder ignore-unresolvable="true" ... />