我正在遵循控制器 -> 服务 -> DAO 模式。当我调用 DAO 实现时,我得到一个 DTO/Data 对象。然后将其传递给服务层,将其各自的业务对象和数据对象组合在一起。像这样:
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());
}
}
有没有我可以遵循的模式来让我做我想做的事?