从Spring'中的属性文件评估属性;s@EventListener(条件=“…”)
我希望事件处理程序的执行取决于属性文件中的属性是否设置为从Spring'中的属性文件评估属性;s@EventListener(条件=“…”),spring,Spring,我希望事件处理程序的执行取决于属性文件中的属性是否设置为true @EventListener(ContextRefreshedEvent.class, condition = "${service.enabled}") public void onStartup() { } 然而,这似乎不起作用。我在启动时遇到以下错误: org.springframework.expression.spel.spelparsexception:EL1043E:(位置1):意外标记。应为'identifier
true
@EventListener(ContextRefreshedEvent.class, condition = "${service.enabled}")
public void onStartup() { }
然而,这似乎不起作用。我在启动时遇到以下错误:
org.springframework.expression.spel.spelparsexception:EL1043E:(位置1):意外标记。应为'identifier',但为'lcurly({)'
是否可以将属性文件中的属性用作此处的条件?问题是条件参数需要SPEL。
这是个好办法,试试看 在您的bean中,您有这个
@EventListener
,添加以下行
public boolean isServiceEnabled() {
return serviceEnabled;
}
@Value("${service.enabled}")
public boolean serviceEnabled;
像这样更改evnt侦听器的声明
@EventListener(classes = ContextRefreshedEvent.class, condition = "@yourbeanname.isServiceEnabled()")
public void onStartup() { }
用正确的bean名称更改BeanName。我也有过同样的恼人经历(Java11上的Spring Boot 2.4.2) 在我的例子中,我在同一个java文件中的
@ConfigurationProperties
类中有boolean
属性,但仍然有点困难。首先,@ConfigurationProperties
需要注释为@Component
,才能真正成为有效的Bean
,并可以在SpEL中使用。
我必须对服务
本身中的ConfigurationProperties
使用相同的长attributeName,并对EventListener
注释使用相同的attributeName,以便Bean解析正常工作。我还需要在服务
的另一个位置使用一些ConfigurationProperties
值,这就是为什么它们需要e(构造器)自动连线
这对我来说很有效:
@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
}
}
我认为在SpEL表达式中,可以使用语法
{${numberProperty}+2}
()引用属性(假设numberProperty
是1
)它的计算结果将是3
。但事实证明,条件
不允许使用有效的SpEL表达式。您的解决方法确实有效,看起来就像我提出的解决方法一样。我相信这与不同的上下文有关。另一点是,在appli中,SpEL并不是针对属性进行计算的这太荒谬了!@Aubergine什么是荒谬的?2020年EventListener无法解析${property},我不得不引用一个ConfigurationProperties bean,而Spring中最有趣的部分就是给这些类型提供了Spring生态系统中最长的名称->完整属性路径+完整包名。这太愚蠢了。而这个问答是整个web中唯一一个真正尝试在“条件”内做一些合理事情的问答。