简体   繁体   中英

Spring Service returns null

I've create a Service that contains a list of objects and I want it to be set in 2 other components. One that populates the list in the service and one to use it for sending messages thru a websocket inside the list (WebSocketConnection is an object that has a Session and TextMessage for making connection with a client. Sending messages works as intended and I've tested multiple clients sending messages.

WebSocketSessionService:

public class WebSocketSessionService {

private List<WebSocketConnection> sessions;

public WebSocketSessionService()
{
    sessions = new ArrayList<WebSocketConnection>();
}

public void addNewSession(WebSocketConnection newSession)
{
    sessions.add(newSession);
}

public List<WebSocketConnection> getAllSessions()
{
    return sessions;
}

public WebSocketConnection getSessionInList(WebSocketConnection session)
{
    System.out.println("alsdsada");
    for (WebSocketConnection webSocketConnection : sessions) {
        System.out.println("alsdsada");
        System.out.println(session.getSession().getId());
        System.out.println(webSocketConnection.getSession().getId());
        if(session.getSession().getId().equals(webSocketConnection.getSession().getId()))
        {
            return webSocketConnection;
        }
    }
    WebSocketConnection webSocketConnection = new WebSocketConnection();
    System.out.println(webSocketConnection.isDummy());
    return new WebSocketConnection();
}

public void printAllSessionId()
{
    for (WebSocketConnection webSocketConnection : sessions) {

        System.out.println(webSocketConnection.getSession().getId());
    }
}
}

WebSocketHandler:

 public class WebSocketHandler extends AbstractWebSocketHandler {

@Autowired
public WebSocketSessionService webSocketSessionsService; //HERE

public WebSocketHandler()
{
    this.webSocketSessionsService= new WebSocketSessionService();
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {    

WebSocketConnection newDataRecieved = new WebSocketConnection(session,message);
System.out.println("Created New WebSocketConnection");
if( ! webSocketSessionsService.getSessionInList(newDataRecieved).isDummy())
{
    webSocketSessionsService.getSessionInList(newDataRecieved).addNewMessage(message);
    System.out.println("Added New Message");
}
else
{
    webSocketSessionsService.addNewSession(newDataRecieved);
    System.out.println("Added New Session");
}
webSocketSessionsService.printAllSessionId();




}

@Override
protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws IOException {

}

}

HomeController:

@Controller
@ComponentScan
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

@Autowired
private VehicleService vehicleService;
@Autowired
private GlobalController globalController;

@Autowired
private WebSocketSessionService webSocketSessionsService; //HERE

@RequestMapping(value = {"/vehicle/saveVehicle"}, method = RequestMethod.POST)
public String saveTodo(@ModelAttribute("reqVehicle") Vehicle reqVehicle,
                       final RedirectAttributes redirectAttributes) {
    logger.info("/vehicle/save");
    try {
        reqVehicle.setCreateDate(LocalDateTime.now());
        reqVehicle.setStatus(Status.ACTIVE.getValue());
        reqVehicle.setUserId(globalController.getLoginUser().getId());
        vehicleService.save(reqVehicle);
        redirectAttributes.addFlashAttribute("msg", "success");

        //SEND MSG TO CLIENT THRU SOCKET
        System.out.println("ALL SESSIONS");
        webSocketSessionsService.printAllSessionId(); //NULL POINTER <--


        webSocketSessionsService.getAllSessions().get(0).sendNewTextMessage("Git Good!");


    } catch (Exception e) {
        redirectAttributes.addFlashAttribute("msg", "fail");
        logger.error("save: " + e.getMessage());
    }

    return "redirect:/home";
}
}

I expect to populate inside WebSocketHandler and use in HomeController.

Remove this.webSocketSessionsService= new WebSocketSessionService(); from Constructor of WebSocketHandler .

And then make your WebSocketSessionService a spring managed bean, so add @Service to the class

@Service
public class WebSocketSessionService {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM