如何将属性占位符传递给 YAML 配置文件中的注释? [英] How can I pass properties placeholder to annotations from YAML config file?
问题描述
我想将我的配置属性从 YAML 文件传递给注释值,如下所示:@SendTo(value = "${config.ws.topic}")
,但出现错误
I want to pass my config properties from YAML file to annotations value like this: @SendTo(value = "${config.ws.topic}")
, but get an error
无法解析占位符 config.ws.topic 等..
Could not resolve placeholder config.ws.topic etc ..
我的代码:
@MessageMapping("/chat.register")
@SendTo("${config.websocket.topic}")
public Message addUser(@Payload Message message,
SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username", message.getSender());
return message;
}
Prop-es 文件:
Prop-es file:
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
吗?
Could you please advise me on how to pass the config properties to annotations @SendTo
?
推荐答案
如果你想将值从 application.yml 映射到你的配置类,你可以简单地使用 @Value
来实现这个目的.
If you are trying to map values from application.yml to your configuration class you can simply make use of @Value
for this purpose.
在您的控制器中,只需创建变量,这些变量将保存来自 application.yml
的信息,如下所示
In your controller simply create variables which will hold the information from application.yml
like as specified below
@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:由于以下错误属性值必须是常量,有一个变通办法来解决这个问题.
Edit 1: Due to the following error Attribute value must be constant, there is a work around to solve the issue.
@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;
这篇关于如何将属性占位符传递给 YAML 配置文件中的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!