我正在使用Spring-Websocket,遇到了以下问题:
我试图在@MessageMapping
注释中放置一个占位符,以便从属性中获取URL。它在@RequestMapping
中有效,但在@MessageMapping
中无效。
如果我使用这个占位符,URL是空的。有什么想法或建议吗?
例如:
@RequestMapping(value= "${myProperty}")
@MessageMapping("${myProperty}")
我正在使用Spring-Websocket,遇到了以下问题:
我试图在@MessageMapping
注释中放置一个占位符,以便从属性中获取URL。它在@RequestMapping
中有效,但在@MessageMapping
中无效。
如果我使用这个占位符,URL是空的。有什么想法或建议吗?
例如:
@RequestMapping(value= "${myProperty}")
@MessageMapping("${myProperty}")
Rossen Stoyanchev为@MessageMapping和@SubscribeMapping方法添加了占位符支持。
请参阅Jira问题:https://jira.spring.io/browse/SPR-13271
@RequestMapping
中使用属性占位符,但在@MessageMapping
中不行。这是因为MessageHandler
。因此,我们需要重写默认的MessageHandler
来实现这一点。
WebSocketAnnotationMethodMessageHandler
不支持占位符,您需要自己添加此功能。WebSocketAnnotationMethodMessageHandler
类,它位于与原始类相同的包org.springframework.web.socket.messaging
中,并重写SimpAnnotationMethodMessageHandler
中的getMappingForMethod
方法,内容相同,只是改变了使用此方法构造SimpMessageMappingInfo
的方式(在WebSocketAnnotationMethodMessageHandler
中为private
)。private SimpMessageMappingInfo createMessageMappingCondition(final MessageMapping annotation) {
return new SimpMessageMappingInfo(SimpMessageTypeMessageCondition.MESSAGE, new DestinationPatternsMessageCondition(
this.resolveAnnotationValues(annotation.value()), this.getPathMatcher()));
}
private SimpMessageMappingInfo createSubscribeCondition(final SubscribeMapping annotation) {
final SimpMessageTypeMessageCondition messageTypeMessageCondition = SimpMessageTypeMessageCondition.SUBSCRIBE;
return new SimpMessageMappingInfo(messageTypeMessageCondition, new DestinationPatternsMessageCondition(
this.resolveAnnotationValues(annotation.value()), this.getPathMatcher()));
}
resolveAnnotationValues
方法),因此我们需要使用类似以下的内容:private String[] resolveAnnotationValues(final String[] destinationNames) {
final int length = destinationNames.length;
final String[] result = new String[length];
for (int i = 0; i < length; i++) {
result[i] = this.resolveAnnotationValue(destinationNames[i]);
}
return result;
}
private String resolveAnnotationValue(final String name) {
if (!(this.getApplicationContext() instanceof ConfigurableApplicationContext)) {
return name;
}
final ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) this.getApplicationContext();
final ConfigurableBeanFactory configurableBeanFactory = applicationContext.getBeanFactory();
final String placeholdersResolved = configurableBeanFactory.resolveEmbeddedValue(name);
final BeanExpressionResolver exprResolver = configurableBeanFactory.getBeanExpressionResolver();
if (exprResolver == null) {
return name;
}
final Object result = exprResolver.evaluate(placeholdersResolved, new BeanExpressionContext(configurableBeanFactory, null));
return result != null ? result.toString() : name;
}
PropertySourcesPlaceholderConfigurer
bean。<context:property-placeholder location="classpath:/META-INF/spring/url-mapping-config.properties" />
@Configuration
@PropertySources(value = @PropertySource("classpath:/META-INF/spring/url-mapping-config.properties"))
public class URLMappingConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
注意:在这种情况下,url-mapping-config.properties
文件位于Gradle/Maven项目的src\main\resources\META-INF\spring
文件夹中,并且内容如下所示:
myPropertyWS=urlvaluews
@Controller
public class WebSocketController {
@SendTo("/topic/test")
@MessageMapping("${myPropertyWS}")
public String test() throws Exception {
Thread.sleep(4000); // simulated delay
return "OK";
}
}
MessageHandler
,启动日志将打印如下内容:INFO: Mapped "{[/${myPropertyWS}],messageType=[MESSAGE]}" onto public java.lang.String com.brunocesar.controller.WebSocketController.test() throws java.lang.Exception
MessageHandler
打印出以下内容:INFO: Mapped "{[/urlvaluews],messageType=[MESSAGE]}" onto public java.lang.String com.brunocesar.controller.WebSocketController.test() throws java.lang.Exception
WebSocketAnnotationMethodMessageHandler
实现。
编辑:此解决方案适用于4.2 GA
之前的版本。有关更多信息,请参见this jira。更新:
现在我明白你的意思了,但我认为这还不可能。
文档中没有提到与路径映射URI相关的任何内容。
旧回答
使用
@MessageMapping("/handler/{myProperty}")
而不是
@MessageMapping("/handler/${myProperty}")
然后像这样使用:
@MessageMapping("/myHandler/{username}")
public void handleTextMessage(@DestinationVariable String username,Message message) {
//do something
}
@MessageMapping("/chat/{roomId}")
public Message handleMessages(@DestinationVariable("roomId") String roomId, @Payload Message message, Traveler traveler) throws Exception {
System.out.println("Message received for room: " + roomId);
System.out.println("User: " + traveler.toString());
// store message in database
message.setAuthor(traveler);
message.setChatRoomId(Integer.parseInt(roomId));
int id = MessageRepository.getInstance().save(message);
message.setId(id);
return message;
}