1.背景
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Value("${spring.rabbitmq.host}")
private String relayHost;
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableStompBrokerRelay("/topic", "/queue")
.setRelayHost(relayHost) // rabbitmq-host服务器地址
.setRelayPort(61613)
.setClientLogin("guest")
.setClientPasscode("guest");
registry.setUserDestinationPrefix("/user/");
registry.setApplicationDestinationPrefixes("/msg");
}
原本想将rabbitmq的主机地址从yml文件中直接获取并赋给relayHost,避免硬编码,但却失败了
Caused by: java.lang.IllegalArgumentException: relayHost must not be empty
四处搜索后发现网上很多的解决方法都不起作用
- 比如加上一个相关的Bean
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
- 又比如实现EnvironmentAware 接口
@Configuration
public class WebsocketConfig implements EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
private void init() {
Optional<String> hostOpt = Optional.ofNullable(environment.getProperty("spring.rabbitmq.host"));
String host = hostOpt.orElse("localhost");
}
...
}
解决方法不适合,感觉头有点大
冷静下后回忆了一下,我原始是用的@Value获取成功的,但是中途在ChannelInterceptor实现类的preSend方法中使用了SimpMessagingTemplate,然后就出现了@Value获取失败的问题!
翻译成人话就是,其他问题引起@Configuration下的配置类生命周期的执行错序,进而引起@Value获取失败
把前面的问题解决后,@Value随之又可以像最初一样可以获取到值了;