加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 自动装配SimpMessagingTemplate

发布时间:2020-12-15 02:11:18 所属栏目:Java 来源:网络整理
导读:我在试图在Service类中使用SimpMessagingTemplate时遇到了麻烦.以下是相关的代码片段: UserService.java – 自动装配失败,template = null @Servicepublic class UserService{ @Autowired private SimpMessagingTemplate template; // Some Code public voi
我在试图在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吗?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读