自动装配SimpMessagingTemplate

6

我在尝试在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的自动装配,在控制器和服务之间有什么区别?非常感谢您能提供任何关于可能发生这种情况的建议。


你能发布一下你的基于注解的Spring配置吗? - Raf
你有没有找到解决方案? - user1102532
1个回答

0

最初,控制器自动装配和服务自动装配之间没有任何区别(如果SimpMessagingTemplate在控制器中可用,则也必须在服务类中可用),除非Spring未加载服务类。

你如何加载你的bean?也许服务类的包没有被自动扫描覆盖?你是否在上下文XML中定义了你的bean?


因为Spring会自动装配而无需在此情况下进行特定配置,所以它没有特定的配置。正如我所说,在控制器中它运行得非常好,但在我的服务中却不行。@ComponentScan(basePackages = "com.xy.*")已设置为扫描整个项目。 - Lukehey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接