import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
+import static de.juplo.boot.data.jdbc.UserEvent.Type.CREATED;
+import static de.juplo.boot.data.jdbc.UserEvent.Type.DELETED;
+
@RestController
@Transactional
@RequestMapping("/users")
private final UserRepository repository;
+ private final ApplicationEventPublisher publisher;
- public UserController(UserRepository repository) {
+ public UserController(
+ UserRepository repository,
+ ApplicationEventPublisher publisher)
+ {
this.repository = repository;
+ this.publisher = publisher;
}
String sanitizedUsername = UserController.sanitize(username);
User user = new User(sanitizedUsername, LocalDateTime.now(), false);
repository.save(user);
+ publisher.publishEvent(new UserEvent(this, CREATED, sanitizedUsername));
UriComponents uri =
builder
.fromCurrentRequest()
return ResponseEntity.notFound().build();
repository.delete(user);
+ publisher.publishEvent(new UserEvent(this, DELETED, username));
return ResponseEntity.ok(user);
}
--- /dev/null
+package de.juplo.boot.data.jdbc;
+
+import org.springframework.context.ApplicationEvent;
+
+
+public class UserEvent extends ApplicationEvent
+{
+ public enum Type { CREATED, LOGIN, LOGOUT, DELETED }
+
+ final Type type;
+ final String user;
+
+
+ public UserEvent(Object source, Type type, String user)
+ {
+ super(source);
+ this.type = type;
+ this.user = user;
+ }
+}
--- /dev/null
+package de.juplo.boot.data.jdbc;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.event.EventListener;
+import org.springframework.stereotype.Component;
+
+@Component
+public class UserEventListener
+{
+ private static final Logger LOG = LoggerFactory.getLogger(UserEventListener.class);
+
+
+ @EventListener
+ public void onUserEvent(UserEvent event)
+ {
+ LOG.info("{}: {}", event.type, event.user);
+ }
+}