我在试图在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();
}
}
所以基本上自动装配在我的Controller类中工作,但不在我的服务中.我需要在服务中手动调用convertAndSendToUser.在控制器和服务之间自动装配SimpMessagingTemplate有什么区别?关于为什么会发生这种情况的任何意见都非常感谢
最初控制器自动装配和服务自动装配之间没有任何区别(如果控制器中有SimpMessagingTemplate,它也必须在服务类中可用),除非spring没有加载服务类.
你如何装豆?也许自动扫描不包括服务类包?你在上下文XML中定义bean吗?