6

I'd like to modify how my application works depending on whether the --debug switch is present or not. I tried this in my @Configuration file:

@Value("\${debug}")
lateinit var debug: String

but Spring says

Could not resolve placeholder 'debug' in value "${debug}"

How can I query the state of the --debug option?

StanislavL
  • 56,971
  • 9
  • 68
  • 98
Adam Arold
  • 29,285
  • 22
  • 112
  • 207

4 Answers4

12

The most robust way to check for debug mode is to query the Environment. This will allow you to detect that the mode has been enabled whether that's been done via a command line argument (--debug), system property (-Ddebug), environment variable (DEBUG=true), etc.

You can inject an instance of the Environment as you would any other dependency or you can implement EnvironmentAware. The getProperty(String) method can then be used to retrieve the value of the debug property. Spring Boot treats debug as being enabled if the debug property has a non-null value other than false:

private boolean isSet(ConfigurableEnvironment environment, String property) {
    String value = environment.getProperty(property);
    return (value != null && !value.equals("false"));
}
Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
0

I am afraid it is not possible to get debug mode this way.

Spring looks for any property values here but --debug is not part of property.

The debug detecting could be vendor specific. (see Determine if a java application is in debug mode in Eclipse for more info about debug detecting).

StanislavL
  • 56,971
  • 9
  • 68
  • 98
0

the simplest way is makes debug option to a system property, for example:

java -Ddebug Application

then you can annotated the property as below:

@Value("#{systemProperties.debug != null}")
var debug: Boolean = false;
//                    ^--- using a default value to avoiding NPException
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • I don't think this will work because the `--debug` option is a special flag handled by Spring. I can't use it in another way. – Adam Arold Jun 19 '17 at 20:25
  • @AdamArold sir, thanks for your feedback. but the `--debug` option only available in `spring-boot` rather than `spring`. – holi-java Jun 19 '17 at 20:33
  • That's why I tagged my question with it. – Adam Arold Jun 19 '17 at 20:38
  • @AdamArold sir, I'm sorry I don't see the title clearly. but you can change other names for the debug, e.g: `dev`. for the option `debug!` you need change the expression to `systemProperties['debug!'] != null`. – holi-java Jun 19 '17 at 20:42
0

As already mentioned before in the reply by Andy, it is possible to evaluate the property debug, however you need to do this from the Environment.

I ran into the same problem, when I wanted to activate a component, only in "debug mode". You can achieve this by using @ConditionalOnProperty("debug"), which does fetch the information from Environment and thus works with --debug, -Ddebug, …

ctron
  • 538
  • 3
  • 13