在 spring 中验证构造函数

validate on constructor in spring

问题真的很短。这两者之间有什么区别吗?如果不是,你用哪个?

第一个:

private final UserRepository UserRepository;
private final UserService userService;

@Autowired
public UserServiceImpl(UserRepository userRepository, UserService userService) {
    Validate.notNull(this.userRepository = userRepository, "user cannot be null");
    Validate.notNull(this.userService = userService, "userService cannot be null");
}

第二个:

@Autowired
public WorkingTimeServiceImpl(UserRepository userRepository, UserService userService) {
    Validate.notNull(userRepository, "userRepository cannot be null");
    Validate.notNull(userService, "userService cannot be null");
    this.userRepository = userRepository;
    this.userService = userService;
}

事实上,这里的 null 验证是无用的,因为它从未使用过,通过在构造函数中放置自动装配,spring 会按照文档中的解释为您检查它们

The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null.

现在我们假设您对方法执行相同的模式,在这种方法中我使用第二种方法,因为它使我能够将我的验证代码与我的属性 bean 分开,所以在任何时候当逻辑变得更复杂时我可以简单地将验证逻辑放在另一个class中,通常我在空验证后添加更多验证规则

一般规则任何验证过程都不需要了解您的属性的任何信息