how to define not mandatory property in spring?

Viewed 17467

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?

3 Answers

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;
}
Related