问题
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?
回答1:
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"));
}
回答2:
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).
回答3:
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
回答4:
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
, …
来源:https://stackoverflow.com/questions/44629885/how-can-i-tell-whether-my-spring-boot-application-is-in-debug-mode