35

I'm using spring 3 with 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.

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

Julias
  • 5,752
  • 17
  • 59
  • 84

3 Answers3

69

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

tibtof
  • 7,857
  • 1
  • 32
  • 49
12

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" ... />
adamoldak
  • 624
  • 6
  • 5
  • In this case all the properties will be not mandatory, But I want only some selected properties be optional, and the rest be mandatory. Can I do this with some annotation? – Julias Aug 02 '12 at 09:37
  • you can write separate property-placeholder for that – Ajeetkumar Aug 02 '16 at 07:49
0

To ignore all unresolvable properties rather than a specific property, you can use the below bean in your configuration class:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setIgnoreUnresolvablePlaceholders(true);
    return configurer;
}
Vinu Dominic
  • 1,040
  • 1
  • 16
  • 25