0

Using a application.properties file my Spring Boot app can use some property values in it. A way to make sure a mandatory value must present is to add an annotation @Value for the property. The problem with this is the app fails miserably if the property value is not there in the properties file.

I am after a nicer less horrible way to say printing out a log line about "Property A is missing" instead of a whole stack trace. Is there a way to do this while still using @Value to initialise the properties? For example, property A is mandatory, an error is logged before app exits; property B is missing but not mandatory, a warning is logged and app continues.

user1589188
  • 5,316
  • 17
  • 67
  • 130

2 Answers2

2

If you can identify all property, then you can write a method in Application class with @Postconstruct, and inside your method, you can manually validate and log them

@Autowired
    private Environment environment;

    @PostConstruct
    private void validateProperties() {

        environment.getProperty(key);
        .....
        ......
    }

Alternatively, you can write your custom EnvironmentPostProcessor, and iterate all properties and log whichever is null/empty.

Shailesh Chandra
  • 2,164
  • 2
  • 17
  • 25
0

As you're using spring-boot consider creating a @ConfigurationProperties class rather than using the @Value annotation.

By doing that you can do your validations using Bean Validation, also in the same class, you can implement the interface InitializingBean and add extra validations/log messages as you with.

Follow this link on Spring's official docs to read more about @ConfigurationProperties.

Marcos Barbero
  • 1,101
  • 8
  • 14