在Spring的@EventListener中评估属性文件中的属性(condition =" ...")

时间:2018-06-06 14:51:11

标签: spring

我想根据属性文件中的属性是否设置为true来执行事件处理程序。

@EventListener(ContextRefreshedEvent.class, condition = "${service.enabled}")
public void onStartup() { }

但是,这似乎不起作用。我在启动时收到以下错误:

  

org.springframework.expression.spel.SpelParseException:EL1043E:(pos 1):意外的令牌。预期的标识符'但是好像({)'

是否可以将属性文件中的属性用作条件?

2 个答案:

答案 0 :(得分:0)

问题是条件论证期待SPEL 这个工作尝试了。

在您拥有此@EventListener的bean中,添加以下行

public  boolean isServiceEnabled() {
    return serviceEnabled;
  }

@Value("${service.enabled}")
public  boolean serviceEnabled;

像这样改变你的evnt听众声明

@EventListener(classes = ContextRefreshedEvent.class, condition =  "@yourbeanname.isServiceEnabled()")
public void onStartup() { }

使用正确的bean名称更改yourbeanname。

答案 1 :(得分:0)

我也有同样烦人的经历(在 Java11 上使用 Spring Boot 2.4.2)。

就我而言,我在同一个 java 文件中的 boolean 类中有 @ConfigurationProperties 属性,但仍然有点挣扎。首先,需要将 @ConfigurationProperties 注释为 @Component 才能真正成为有效的 Bean,并且可以在 SpEL 中使用。 而且我必须对 ConfigurationProperties 本身中的 ServiceEventListener 注释使用相同的长属性名称才能使 Bean 解析正常工作。我还需要在 ConfigurationProperties 的另一个地方使用一些 Service 值,这就是为什么它们也需要是(构造函数)Autowired...

所以这对我有用:

@ConfigurationProperties("my.custom.path")
@Component //Important to make this a proper Spring Bean
@Data //Lombok magic for getters/setters etc.
class MyCustomConfigurationProperties {
    boolean refreshAfterStartup = true;
}

@Service
@RequiredArgsConstructor //Lombok for the constructor
@EnableConfigurationProperties(MyCustomConfigurationProperties.class)
@EnableScheduling
public class MyCustomService {
    private final MyCustomConfigurationProperties myCustomConfigurationProperties;

    @EventListener(value = ApplicationReadyEvent.class, condition = "@myCustomConfigurationProperties.refreshAfterStartup")
    public void refresh() {
       //the actual code I want to execute on startup conditionally
    }
}