设计一个新的应用程序,我有两组域对象。一组镜像另一组,域对象基本上与相似的属性配对。当集合A中的域对象被创建、更新或删除时,集合B中对应的域对象也将被创建、更新或删除。为了减少任何耦合,我想将一对域对象之间的这些操作分开。实现这一方法的良好机制是什么?我正在考虑使用消息系统。对于这种情况,它会有效吗?我在这个项目中使用 Spring。
最佳答案
是的,使用应用程序事件是减少对象之间耦合的常见解决方案。
实际上 Spring 已经有内置的机制了。
你可能会想出类似的东西:
@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
也有相应的工具。
关于java - 对象镜像其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490189/