Search code examples
javaspringspring-aopspring-annotations

Exception as default value of Spring @Value()


I'm new to Java/Spring. I need to read some value from config but if it doesn't exist it should fails. For now I have the following code:

public class SomeClass {

    @Value("${some.property:#{null}}")
    private String someProperty;

    public void someMethod() throws Exception {
        if (someProperty == null) throw new AopConfigException("The property must be set");
    }

}

It works fine but I need to add additional if block. Could I write something like that?

@Value("${some.property:#{throw new AopConfigException(\"The property must be set\")}}")
private String someProperty;

or

@Value("${some.property:#{throwException()}}")
private String someProperty;

private static void throwException() {
    throw new AopConfigException("The property must be set");
}

to fail immediately

Upd: If I don't use some default value as suggested below then it still doesn't fail for me. I don't have java.lang.IllegalArgumentException:

enter image description here


Solution

  • In order for the property replacement to work you will need to add a PropertySourcesPlaceholderConfigurer bean to your configuration like this (example taken from here):

    @Bean
    public static PropertySourcesPlaceholderConfigurer properties(){
      final PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
      // add your property files below
      final Resource[] resources = new ClassPathResource[]{new ClassPathResource("foo.properties")};
      pspc.setLocations( resources );
      // this will make the replacement fail, if property is not known
      pspc.setIgnoreUnresolvablePlaceholders(false); 
      return pspc;
    }
    

    If you already configure your property sources with @PropertySource annotations you should be able to omit adding the resources to the PropertySourcesPlaceholderConfigurer manually as it should pickup values from the spring environment automatically.

    Once this bean is in place simply use

    @Value("${data.import.path}")
    

    without default (as already mentioned in the other answers) and initialization of your application will fail at a very early stage.