我在尝试在Service类中使用SimpMessagingTemplate时遇到了麻烦。以下是相关的代码片段:
UserService.java - 自动装配失败,template = null
@Service
public class UserService{
@Autowired
private SimpMessagingTemplate template;
// Some Code
public void tellUser(String username, String url) {
// This is always true
System.out.println("TEMPLATE NULL? " +(this.template == null));
// Further code omitted
}
}
SocketController.java - 自动装配正常,Spring Websockets按预期工作。
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate template;
public void tellUser(String username, String url) {
// False here, template is autowired correctly
System.out.println("TEMPLATE NULL? " +(this.template == null));
this.template.convertAndSendToUser(username, "/test/notify", new Greeting("USER SPECIFIC MESSAGE: " + url));
}
}
WebSocketConfig.java
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/user", "/test");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/test").withSockJS();
}
}
简单来说,我的控制器类中的自动装配是有效的,但我的服务类中不起作用。在服务中,我需要手动调用convertAndSendToUser。对于SimpMessagingTemplate的自动装配,在控制器和服务之间有什么区别?非常感谢您能提供任何关于可能发生这种情况的建议。