0

Using the @Value annotation, is there any way to check (other than if-statements) if spring failed to do the injection and defaulted to null? Say, for example, you're doing it for 10+ variables; it would be rather extensive to go through the chain of if-statements. My intention is to track which failed, and throw an exception listing them. If possible, I'd rather not use reflection but I wouldn't mind if it was cleaner than a chain of if-statements.

UPDATE

Here's an example:

@Value("${my.package.username:#{null}}")
private String username;

When my.package.username isn't defined for Spring as my.package.username=someUserName in application.properties or as a JVM argument for Tomcat to pick it up in the form of
-Dmy.package.username=someUserName then it should default to null, which it does. Now, imagine there are 10+ of the above declaration for different variables, I would like to know how to determine which are null without checking each one. I was thinking there may be functionality in Spring to determine which failed since spring is doing the injection.

Darrel Holt
  • 870
  • 1
  • 15
  • 39
  • 2
    Spring will fail starting the app if it can't find a property value. Unless you've explicitely told him to ignore unmatched properties. See this answer : https://stackoverflow.com/questions/29798190/how-to-make-simple-property-validation-when-using-spring-value – Thoomas Jul 25 '17 at 06:39
  • @Thoomas, I think you misunderstood my question, I updated it with an example. – Darrel Holt Jul 25 '17 at 15:25
  • https://softwareengineering.stackexchange.com/questions/296707/throwing-an-exception-if-some-property-is-not-present-in-a-properties-file check out the first answer – dannemp Jul 25 '17 at 15:28
  • thanks @dannemp, but I'm looking for something specific to Spring since I'm using the `@Value` annotation to do dependency injection – Darrel Holt Jul 25 '17 at 15:38

1 Answers1

1

Spring treats "environment" as a normal property source, so it will not care too much from which property source came the final value. In the example you gave you use null as fallback value, so you do a little opposite to what you would like to achieve.

But there are i think some tricks:

1) try to set some spring classes logging to DEBUG or even TRACE, maybe in logs it will be possible to find the information you want

2) if you want to know that within the program, then you really need to have distinction between the file property source and other, and do few ifs...

Tomasz
  • 988
  • 1
  • 9
  • 23