Using Services to encapsulate business logic

It is a good practice to encapsulate business logic inside Service methods so that controllers and repositories are loosely coupled. The following Service is written to encapsulate the business logic for User:

Service
@Transactional(readOnly = true)
public class UserService implements UserDetailsService {

private final UserRepository userRepository;

public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}

public User getByEmail(String email) {
return userRepository.findByEmail(email);
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);

if (user == null) {
throw new UsernameNotFoundException(username);
}

return new org.springframework.security.core.userdetails.User(username, user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
}

@Transactional(rollbackFor = Exception.class)
public User save(User user) {
return userRepository.save(user);
}

public List<User> getAll() {
return userRepository.findAll();
}
}

UserService also implements the Spring Security UserDetailsService interface in addition to supporting User detail loading. The save method saves a User instance in the database, getByEmail retrieves the User by email, and the getAll method retrieves all the users. More on this will be discussed in the Using Spring Security for authentication and authorization section of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.124.194