我遵循 Controller -> 服务 -> DAO 模式。当我调用 DAO 实现时,我会返回一个 DTO/数据对象。然后它被传递到服务层,将其各自的业务对象和数据对象组合在一起。就像这样:
public User getUserById(int id) {
return new User(userDAO.getUserById(id));
}
class User {
private UserDTO userDTO;
public User(UserDTO userDTO) {
this.userDTO = userDTO;
}
}
我想做的是将所有业务逻辑包装在业务类中,但我需要额外的依赖项。 例如,我希望能够做这样的事情:
//... some code
User user = userService.getByUserId(1);
user.delete(); // this should delete the user from the database
为了让我以这种方式删除用户,我需要将 UserService 自动连接到业务类中,但这不起作用,因为我是在用户服务中手动实例化 User 类。
class User {
@Autowired
private UserService userService; // this won't work since I call instantiate User myself, ie. new User()
private UserDTO userDTO;
public User(UserDTO userDTO) {
this.userDTO = userDTO;
}
public boolean delete() {
userService.deleteByUserId(userDTO.getId());
}
}
是否有一个我可以遵循的模式来让我做我想做的事?
最佳答案
我认为将商务类作为 DTO 对象的成员不是一个好的设计。 更合适的方法是将删除方法放在业务类中。这将有助于松散耦合。
关于java - 如何在 Spring 中 Autowiring 业务对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455878/