How can I pass properties placeholder to annotations from YAML config file?

旧巷老猫 提交于 2020-05-17 06:26:07

问题


I want to pass my config properties from YAML file to annotations value like this: @SendTo(value = "${config.ws.topic}"), but get an error

Could not resolve placeholder config.ws.topic etc ..

My Code:

@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 file:

server:
  address: 127.0.0.1
  port: 8080

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

Props config class:

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;
} 
}

Could you please advise me on how to pass the config properties to annotations @SendTo?


回答1:


If you are trying to map values from application.yml to your configuration class you can simply make use of @Value for this purpose.

In your controller simply create variables which will hold the information from application.yml like as specified below

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

and your controller will look as below

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

}

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;

and your controller will look as below

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




来源:https://stackoverflow.com/questions/57677433/how-can-i-pass-properties-placeholder-to-annotations-from-yaml-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!