设计一个新的应用程序,我有两组域对象。一组镜像另一组,域对象基本上与相似的属性配对。当创建,更新或删除集合A中的域对象时,还将创建,更新或删除集合B中的相应域对象。为了减少任何耦合,我想在一对域对象之间分离这些操作。实现这种方法的好机制是什么?我正在考虑使用消息传递系统。它会适用于这种情况吗?我在这个项目中使用Spring。
答案 0 :(得分:1)
是的,使用应用程序事件是减少对象之间耦合的常用解决方案。
实际上,春天已经有了内置机制。
你可能想出类似的东西:
@SpringBootApplication
public class So44490189Application {
public static void main(String[] args) {
SpringApplication.run(So44490189Application.class, args);
}
public static class UserCreatedEvent {
private final String email;
public UserCreatedEvent(String email) {
this.email = email;
}
}
@Service
public static class UserService {
@EventListener
public void handleUserCreatedEvent(UserCreatedEvent userCreatedEvent) {
System.out.println("Creating user " + userCreatedEvent.email);
}
}
@Service
public static class MemberService {
@EventListener
public void handleUserCreatedEvent(UserCreatedEvent userCreatedEvent) {
System.out.println("Creating member " + userCreatedEvent.email);
}
}
@Service
public static class OperationService {
private final ApplicationEventPublisher eventPublisher;
@Autowired
public OperationService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void createUser(String email) {
eventPublisher.publishEvent(new UserCreatedEvent(email));
}
}
@RestController
public static class OperationController {
private final OperationService operationService;
@Autowired
public OperationController(OperationService operationService) {
this.operationService = operationService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void createUser(String email) {
operationService.createUser(email);
}
}
}
用法
curl -XPOST 'localhost:8080?email=admin@localhost.localdomain'
输出
Creating member admin@localhost.localdomain
Creating user admin@localhost.localdomain
在这种情况下,创建用户和成员是镜像的。
一个可能的问题是交易支持,有几种方法可以解决这个问题。 Spring
也有工具。