degath
degath

Reputation: 1621

validate on constructor in spring

The question is really short. Is there any difference between those two? If no, which one you use?

First one:

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");
}

Second one:

@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;
}

Upvotes: 0

Views: 596

Answers (1)

elmehdi
elmehdi

Reputation: 479

In Fact the validation of null here is useless because it never used, by placing autowired in constructor the spring check them for you as they explain in doc

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.

Now we suppose you do the same pattern for method, in this approach I use the second one because it make me able to separate my validation code from my properties beans, so at any time when the logic become more complex i can simply put the validation logic in another class, which generally i add more validation rule after null verification

General rule any validation process dont need to know anything about your properties

Upvotes: 1

Related Questions