66import org .springframework .context .annotation .ScopedProxyMode ;
77import org .springframework .security .core .userdetails .UserDetailsService ;
88import org .springframework .security .core .userdetails .UsernameNotFoundException ;
9+ import org .springframework .security .crypto .password .PasswordEncoder ;
910import org .springframework .stereotype .Service ;
1011import org .springframework .transaction .annotation .Transactional ;
1112import org .springframework .util .Assert ;
1718
1819import java .util .List ;
1920
21+ import static ru .javawebinar .topjava .util .UsersUtil .prepareToSave ;
2022import static ru .javawebinar .topjava .util .ValidationUtil .checkNotFound ;
2123
2224@ Service ("userService" )
2325@ Scope (proxyMode = ScopedProxyMode .TARGET_CLASS )
2426public class UserService implements UserDetailsService {
2527
2628 private final UserRepository repository ;
29+ private final PasswordEncoder passwordEncoder ;
2730
28- public UserService (UserRepository repository ) {
31+ public UserService (UserRepository repository , PasswordEncoder passwordEncoder ) {
2932 this .repository = repository ;
33+ this .passwordEncoder = passwordEncoder ;
3034 }
3135
3236 @ CacheEvict (value = "users" , allEntries = true )
3337 public User create (User user ) {
3438 Assert .notNull (user , "user must not be null" );
35- return repository . save (user );
39+ return prepareAndSave (user );
3640 }
3741
3842 @ CacheEvict (value = "users" , allEntries = true )
@@ -58,16 +62,15 @@ public List<User> getAll() {
5862 public void update (User user ) {
5963 Assert .notNull (user , "user must not be null" );
6064// checkNotFound : check works only for JDBC, disabled
61- repository . save (user );
65+ prepareAndSave (user );
6266 }
6367
6468
6569 @ CacheEvict (value = "users" , allEntries = true )
6670 @ Transactional
6771 public void update (UserTo userTo ) {
6872 User user = get (userTo .id ());
69- User updatedUser = UsersUtil .updateFromTo (user , userTo );
70- repository .save (updatedUser ); // !! need only for JDBC implementation
73+ prepareAndSave (UsersUtil .updateFromTo (user , userTo ));
7174 }
7275
7376 @ CacheEvict (value = "users" , allEntries = true )
@@ -87,6 +90,10 @@ public AuthorizedUser loadUserByUsername(String email) throws UsernameNotFoundEx
8790 return new AuthorizedUser (user );
8891 }
8992
93+ private User prepareAndSave (User user ) {
94+ return repository .save (prepareToSave (user , passwordEncoder ));
95+ }
96+
9097 public User getWithMeals (int id ) {
9198 return checkNotFound (repository .getWithMeals (id ), id );
9299 }
0 commit comments