Building a Real-Time Notification System with Spring Boot and WebSockets
- Java Spring Boot
Team CNC
- 28 February 2025
- 0
- 4 minutes read
Real-time notifications enhance user experience by providing instant updates. WebSockets enable bidirectional communication between the server and clients, making them ideal for real-time applications. This guide explains how to build a notification system in Spring Boot using WebSockets step by step.
1. Add Required Dependencies
Include WebSocket dependencies in pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
2. Enable WebSockets in Spring Boot
Create a configuration class to enable WebSockets:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
}
}
3. Create a Notification Model
Define a simple notification object:
public class Notification {
private String message;
public Notification() {}
public Notification(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
4. Create a Notification Controller
This controller sends notifications to connected clients:
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class NotificationController {
@MessageMapping("/notify")
@SendTo("/topic/notifications")
public Notification sendNotification(String message) {
return new Notification("New Notification: " + message);
}
}
5. Create a Simple Frontend (HTML + JavaScript)
Create an index.html
file for testing WebSocket notifications:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Notifications</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.1/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<h2>WebSocket Notifications</h2>
<button onclick="sendNotification()">Send Notification</button>
<ul id="notifications"></ul>
<script>
let socket = new SockJS('/ws');
let stompClient = Stomp.over(socket);
stompClient.connect({}, function () {
stompClient.subscribe('/topic/notifications', function (message) {
let notification = JSON.parse(message.body);
let li = document.createElement("li");
li.textContent = notification.message;
document.getElementById("notifications").appendChild(li);
});
});
function sendNotification() {
stompClient.send("/app/notify", {}, "Hello WebSocket");
}
</script>
</body>
</html>
6. Running and Testing the Application
Start the Spring Boot application.
Open the
index.html
file in a browser.Click the “Send Notification” button to test real-time notifications.
Conclusion
By implementing WebSockets in Spring Boot, you can create a real-time notification system that enhances user engagement. You can further extend this by integrating it with user authentication and a database for persistent notifications.