Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate property from properties file in Spring's @EventListener(condition = "...")

Tags:

spring

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?

like image 846
Stefan van den Akker Avatar asked Jun 06 '18 14:06

Stefan van den Akker


People also ask

How use value from properties file in Spring boot?

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.

How do you access a value defined in the application properties 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.

How do you load properties file based on environment in Spring boot?

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.

How read data from application properties file in Spring?

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.


1 Answers

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 .

like image 107
pvpkiran Avatar answered Sep 30 '22 10:09

pvpkiran