Search code examples
javaspringspring-bootspring-websocket

How do I share an object between two or more WebSocket controllers in Spring Boot?


I have two controllers, namely ControllerA and ControllerB. In ControllerA I have an object (a HashMap) which maps principal names for connected users to their respective usernames:

@Controller
public class ControllerA {
    HashMap<String, String> principalToUsername = new HashMap<>();
    ...
}

I would like to be able to access this object from ControllerB, which is another websocket controller:

@Controller
public class ControllerB {
    private String getUsername(String principalName) {
        // I want to access usernames here
    }
}

How can I do this? All posts I've read speak about MVC controllers, in which I can use @SessionVariable or flash attributes. But how do I accomplish the same with WebSocket controllers?


Solution

  • You could create an additional @Component which keeps the HashMap<> and autowire it into both controllers. Be aware that by default, this will be shared by all controllers in the Spring application.

    @Component
    public class UserMap {
        private final Map<String, String> map = new HashMap<>();
    
        public String getUserName(String userName) {
            return map.get(userName);
        }
    }
    

    In the controller;

    private final UserMap userMap;
    
    // autowire in constructor
    public ControllerA(UserMap userMap) {
        this.userMap = userMap;
    }
    
    private String getUsername(String principalName) {
        userMap.getUserName(principalname);
    }