【问题标题】:How can I pass properties placeholder to annotations from YAML config file?如何将属性占位符传递给 YAML 配置文件中的注释?
【发布时间】:2019-08-27 14:55:52
【问题描述】:

我想将我的配置属性从 YAML 文件传递​​给注释值,如下所示:@SendTo(value = "${config.ws.topic}"),但出现错误

无法解析占位符 config.ws.topic 等 ..

我的代码:

@MessageMapping("/chat.register")
@SendTo("${config.websocket.topic}")
public Message addUser(@Payload Message message,
                       SimpMessageHeaderAccessor headerAccessor) {
    headerAccessor.getSessionAttributes().put("username", message.getSender());
    return message;

}

属性文件:

server:
  address: 127.0.0.1
  port: 8080

config:
  websocket:
    endpoint: /ns/ws/endpoint
    appPrefix: /ns/ws
    topic: /ns/ws/ns-topic

道具配置类:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(value = "config.websocket")
public class WebSocketConfigurationProperties {
  private String endpoint;
  private String appPrefix;
  private String topic;

public String getEndpoint() {
    return endpoint;
}

public void setEndpoint(String endpoint) {
    this.endpoint = endpoint;
}

public String getAppPrefix() {
    return appPrefix;
}

public void setAppPrefix(String appPrefix) {
    this.appPrefix = appPrefix;
}

public String getTopic() {
    return topic;
}

public void setTopic(String topic) {
    this.topic = topic;
} 
}

您能否告诉我如何将配置属性传递给注释@SendTo

【问题讨论】:

  • 你到底想做什么?您是否正在尝试将 application.yml 中的值映射到您的 props cofig 类?
  • @Coder 我只想将值从 application.yml 设置到我的控制器类,即注释。我想将应用程序 yaml (namly config.websocket.topic) 中的值映射到我的控制器类中的注释 SendTo。我想这样做是因为当我在属性配置文件中更改主题的名称时,它也在控制器类中发生了更改。

标签: java spring-boot annotations


【解决方案1】:

如果您尝试将值从 application.yml 映射到您的配置类,您可以简单地使用 @Value 来实现此目的。

在您的控制器中,只需创建将保存来自application.yml 的信息的变量,如下所示

@Value("${config.ws.topic}")
String topic;

您的控制器将如下所示

@MessageMapping("/chat.register")
@SendTo(topic)
public Message addUser(@Payload Message message,
                       SimpMessageHeaderAccessor headerAccessor) {
    headerAccessor.getSessionAttributes().put("username", message.getSender());
    return message;

}

编辑1:由于以下错误属性值必须是常量,有一个变通方法来解决这个问题。

@Value("${config.ws.topic}")
String topic;

public static final String TOPIC_VALUE = "" + topic;

您的控制器将如下所示

@MessageMapping("/chat.register")
@SendTo(TOPIC_VALUE)
public Message addUser(@Payload Message message,
                       SimpMessageHeaderAccessor headerAccessor) {
    headerAccessor.getSessionAttributes().put("username", message.getSender());
    return message;


【讨论】:

  • 我尝试这样做但得到编译错误“属性值必须是常量”
  • 非常感谢!但是,我认为这 (public static final String TOPIC_VALUE = "" + topic;) 是不好的做法,因为我得到了编译错误:非静态字段不能被引用等。我希望找到更专业的方法。
  • 这肯定不是一个好习惯。我只是将它作为一种解决方法包括在内,但欢迎提出建议。甚至我更喜欢学习:)
猜你喜欢
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 2022-06-20
相关资源
最近更新 更多