I would like to make the execution of an event handler dependent on whether or not a property is set to true
in a properties file.
@EventListener(ContextRefreshedEvent.class, condition = "${service.enabled}")
public void onStartup() { }
However, this does not seem to work. I am getting the following error on startup:
org.springframework.expression.spel.SpelParseException: EL1043E:(pos 1): Unexpected token. Expected 'identifier' but was 'lcurly({)'
Is it possible to use a property from a properties file as a condition here?
Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.
You can use @Value("${property-name}") from the application. properties if your class is annotated with @Configuration or @Component . You can make use of static method to get the value of the key passed as the parameter.
Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
Another very simple way to read application properties is to use @Value annotation. Simply annotation the class field with @Value annotation providing the name of the property you want to read from application. properties file and class field variable will be assigned that value.
The issue is condition argument is expecting a SPEL.
This works try it out.
In your bean where you have this @EventListener
, add these lines
public boolean isServiceEnabled() {
return serviceEnabled;
}
@Value("${service.enabled}")
public boolean serviceEnabled;
change your declaration of evnt listener like this
@EventListener(classes = ContextRefreshedEvent.class, condition = "@yourbeanname.isServiceEnabled()")
public void onStartup() { }
change yourbeanname with the correct bean name .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With