【问题标题】:How to autowire @ConfigurationProperties bean into SpEL expression in spring-boot 2.2.*?如何在 spring-boot 2.2.* 中将 @ConfigurationProperties bean 自动连接到 SpEL 表达式中?
【发布时间】:2020-10-08 11:46:17
【问题描述】:

我正在使用 spring boot 2.2.6,正如documentation 所说:

当使用配置属性扫描或通过@EnableConfigurationProperties 注册@ConfigurationProperties bean 时,该bean 有一个常规名称:-,其中是@ConfigurationProperties 注释中指定的环境键前缀,并且是bean 的完全限定名称。如果注解不提供任何前缀,则仅使用 bean 的完全限定名称。

上面示例中的 bean 名称是 acme-com.example.AcmeProperties。

但是,当我使用这个 SpEL 时:@Scheduled(fixedDelayString = "#{@(mr-my.config.properties.ApplicationProperties).task.get(T(my.config.Constants).CONST).delay}") 我得到一个错误:

Parameter 0 of constructor in my.controllers.Controller required a bean named 'mr' that could not be found.


Action:

Consider defining a bean named 'mr' in your configuration.

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:
    @Scheduled(fixedDelayString = "#{@(mr-my.config.properties.ApplicationProperties).task.get(T(my.config.Constants).CONST).delay}")
    

    @ 表示您需要提供具有给定名称的 bean。

    @Configuration
    class SchedulerConfig{
    
     @Bean
      public String scheduler1Delay() {
         return "500000s";
      }
    }
    

    现在将配置中的bean名称设置为

    @Scheduled(fixedDelayString = "#{@scheduler1Delay}")
    

    【讨论】:

      【解决方案2】:

      提供给 ConfiguiartionProperties 注释的前缀是 bean 的名称。

      例如:

      package com.my.company;
      
      ...
      
      @ConfigurationProperties("alpha.beta.gamma")
      public class TheTimes {
      
          private Duration theInterval = Duration.ofSeconds(30);
      
          // getter and setter
      }
      

      然后

      @Scheduled(fixedDelayString = "#{@'alpha.beta.gamma-com.my.company.TheTimes'.theInterval}")
      

      【讨论】:

        猜你喜欢
        • 2015-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-30
        • 1970-01-01
        • 2018-08-15
        • 1970-01-01
        • 2020-03-03
        相关资源
        最近更新 更多