能否将配置属性值传递给注解,占位符解析报错如何解决
配置属性值传入注解参数的实现方案
错误原因
你当前的写法存在两个核心问题:
- Kotlin/Java 的注解参数要求是编译期常量,你通过
@Autowired注入的config是运行期才完成初始化的Bean,编译阶段无法读取到config.queueName的值 - SpEL 表达式写法错误:
#{${config.queueName}}的嵌套写法会让Spring优先解析内部的${config.queueName}占位符,找不到对应配置项就会抛出你遇到的报错
可行实现方案
方案1:通过@ConfigurationProperties配置类读取
如果队列名已经封装在AppProperties配置类中,直接通过SpEL引用Spring容器中的配置类Bean即可:
- 先确保
AppProperties配置类定义正确:
// prefix替换为你实际的配置前缀 @ConfigurationProperties(prefix = "app") class AppProperties { // 对应配置文件中的app.queue-name配置项 var queueName: String = "" }
- 在启动类/配置类添加注解开启配置类自动装配:
@SpringBootApplication @EnableConfigurationProperties(AppProperties::class) class DemoApplication
- 修正
@RabbitListener注解写法:
// SpEL中通过@+Bean名引用容器中的Bean,配置类默认Bean名为类名小驼峰,即appProperties @RabbitListener(queues = ["#{@appProperties.queueName}"]) fun listen(message: String?) { println(message) }
方案2:直接读取配置文件属性
如果不需要封装配置类,可以直接读取配置文件中的属性,写法更简单:
假设application.yml配置如下:
app: queue-name: custom-rabbit-queue
注解直接写为:
@RabbitListener(queues = ["\${app.queue-name}"]) fun listen(message: String?) { println(message) }
注:Kotlin 字符串中$为特殊字符,需要加反斜杠转义,Java 环境下无需转义直接写${app.queue-name}即可
内容的提问来源于stack exchange,提问作者Hett
相关产品推荐
相关产品推荐

