Home » Java » java – error with userDetailsService org.springframework.beans.factory.UnsatisfiedDependencyException-Exceptionshub

java – error with userDetailsService org.springframework.beans.factory.UnsatisfiedDependencyException-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I wrote a lot of code so I can’t find exactly the code that generates this error but I have been trying to fix it for days without success. This is an error concerning the userDetailsService that I have implemented on userService, the user entity class implements UserDetails and serializable. Please I need help.

the User entity class

@Entity
@Table
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User implements UserDetails, Serializable{

  @Id
  private String matricule;

  private String password;

  private String username;

  private String codeExploitant;

  private Boolean activated;

  @Column(nullable=true)
  private String createdBy;

   @OneToMany(mappedBy="user", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
   private List<UserCaisse> caisses;

   public void addCaisse(Caisse caisse) {
       //recupereration de la date systeme
       LocalDateTime dateTime = LocalDateTime.now();

          UserCaisse userCaisse = new UserCaisse(this, caisse);
          userCaisse.setDate(dateTime);
          caisses.add(userCaisse);
          caisse.getUsers().add(userCaisse);
      }

   public void removeCaisse(Caisse caisse) {
          for (Iterator<UserCaisse> iterator = caisses.iterator();
               iterator.hasNext(); ) {
              UserCaisse userCaisse = iterator.next();

              if (userCaisse.getUser().equals(this) &&
                      userCaisse.getCaisse().equals(caisse)) {
                  iterator.remove();
                  userCaisse.getCaisse().getUsers().remove(userCaisse);
                  userCaisse.setUser(null);
                  userCaisse.setCaisse(null);
              }
          }
   }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
      return null;
  }

  @Override
  public boolean isAccountNonExpired() {
      return false;
  }

  @Override
  public boolean isAccountNonLocked() {
      return false;
  }

  @Override
  public boolean isCredentialsNonExpired() {
      return false;
  }

  @Override
  public boolean isEnabled() {
      return false;
  }
}

the UserService class

@Service
@Slf4j
public class UserService implements UserDetailsService{

    private final IUser userRepository;

    private final ICaisse caisseRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    private User user;

    @Autowired
    public UserService(IUser userRepository, ICaisse caisseRepository) {
        this.userRepository=userRepository;
        this.caisseRepository=caisseRepository;
    }

    //find methods
    public User findById(String matricule) {
        log.info("Selection d'un enregistrement de user a partir du matricule {} effectué avec succès", matricule);
        return userRepository.findById(matricule).orElse(new User());
    }

    public List<User> find(String username) {
        log.info("Selection d'une liste d'enregistrement de user a partir de username effectué avec succès");
        return userRepository.findByUsername(username);
    }

    public List<User> find(){
        List<User> lstUser=userRepository.findAll();

        try {
            lstUser.forEach(item->{
                item.setPassword(null);
            });

            log.info("Selection de tous les users effectué avec succès");
        } catch (Exception e) {
            log.error("Erreur lors de la selection de tous les users {}",e.getMessage());
            System.err.println("Erreur lors de la selection de tous les users "+e.getMessage());
        }

        return lstUser;
    }

    public User getOne(String matricule) {
        log.info("Selection d'un enregistrement de user a partir de matricule: {} effectué avec succès",matricule);
        return userRepository.getOne(matricule);
    }

    //Delete methods
    public boolean delete(String matricule) {
        boolean success=false;

        try {
            if(!StringUtils.isEmpty(matricule)) {
                user=userRepository.findById(matricule).orElse(new User());
                userRepository.deleteById(user.getMatricule());
                success=true;
            }

            log.info("Suppression de l'utilisateur de matricule {} effectuée avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur survenu lors de la suppression de l'enregistrement {} erreur:{}",matricule,e.getMessage());
            System.err.println("Erreur survenu lors de la suppression de l'enregistrement "+matricule+" "+e.getMessage());
        }

        return success;
    }

    public List<Caisse> getCaisseByUser(String matricule){
        List<Caisse> caisses=caisseRepository.findAll();
        User user=userRepository.findById(matricule).orElse(new User());
        List<Caisse> lstCaisses=new ArrayList<Caisse>();

        try {
            List<UserCaisse> uc=user.getCaisses();

            caisses.forEach(item->{
                uc.forEach(data->{
                    if(item.getIdCaisse().equals(data.getId().getIdCaisse())) {
                        lstCaisses.add(item);
                    }
                });
            });

            log.info("Recuperation d'une liste de caisse selon l'utlisateur {} effectué avec succès",matricule);
        } catch (Exception e) {
            log.error("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur");
            System.err.println("Erreur lors de la recuperation de la liste de caisse selon l'utilisateur "+e.getMessage());
        }

        return lstCaisses;
    }

    //save
    public User save(User user, String mode) {
        User u=new User();

        try {
            if(mode=="create") {
                //cryptage de password
                String passwordEncrypt=passwordEncoder.encode(user.getPassword());
                user.setPassword(passwordEncrypt);
                u=userRepository.save(user);
            }
            else if(mode=="update"){
                if(user.getPassword()==null) {
                    User getUser=userRepository.findById(user.getMatricule()).orElse(new User());
                    user.setPassword(getUser.getPassword());
                }else {
                    user.setPassword(passwordEncoder.encode(user.getPassword()));
                }

                u=userRepository.save(user);
            }else{
                u=userRepository.save(user);
            }

            log.info("Enregistrement de l'utilisateur {} effectué avec succès",u.getMatricule());
        } catch (Exception e) {
            log.error("Erreur survenu lors de l'enregistrement des données de l'utilisateur {}",user.getMatricule());
            System.err.println("Erreur survenu lors de l'enregistrement des données de l'utilisateur "+user.getMatricule());
        }

        return u;
    }

    public boolean verifPassword(String password, String matricule) {
        boolean success=false;

        try {
            User u=userRepository.findById(matricule).orElse(new User());
            success=passwordEncoder.matches(password, u.getPassword());
            log.info("Verification du mot de passe effectué avec succès");
            success=true;
        } catch (Exception e) {
            log.info("Echec de la verification du mot de passe {}",e.getMessage());
            System.err.println("Echec de la verification du mot de passe "+e.getMessage());
            success=false;
        }

        return success;
    }

    //edit methods
    public void editUser(String username, String codeExploitant, String matricule) {
        log.info("Modification de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateUser(username, codeExploitant, matricule);
    }

    public void editPassword(String password, String matricule) {
        log.info("Modification du mot de passe de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updatePassword(password, matricule);
    }

    public void editEtat(boolean etat, String matricule) {
        log.info("Modification de l'etat de l'utilisateur {} effectué avec succès",matricule);
        userRepository.updateEtatActivated(etat, matricule);
    }

    //Login
    @Override
    public UserDetails loadUserByUsername(String matricule) throws UsernameNotFoundException {

        Objects.requireNonNull(matricule);

        log.info("Chargement des informations de l'utilisateur {} effectué avec succès",matricule );
        User user = userRepository.findUserWithMatricule(matricule)
                .orElseThrow(() -> new UsernameNotFoundException("User non trouvé"));

        return user;
    }

}

the WebSecurityConfig class

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new AccessDeniedHandler() {

            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response,
                    AccessDeniedException accessDeniedException) throws IOException, ServletException {
            }
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
        configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new Http403ForbiddenEntryPoint() {
                })
                .and()
                .authenticationProvider(getProvider())
                .formLogin()
                .loginProcessingUrl("/login")
                .passwordParameter("password")
                .usernameParameter("username")
                .successHandler(new AuthentificationLoginSuccessHandler())
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new AuthentificationLogoutSuccessHandler())
                .invalidateHttpSession(true)
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/user").authenticated()
                .anyRequest().permitAll();
    }

    private class AuthentificationLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    private class AuthentificationLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
        @Override
        public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    @Bean
    public AuthenticationProvider getProvider() {
        AppAuthProvider provider = new AppAuthProvider();
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }
}

the IUser repository class

@Repository
public interface IUser extends JpaRepository<User, String>{

    public List<User> findByUsername(String username);

    public List<User> findAll();

    @Query("SELECT u FROM User u WHERE u.matricule=:matricule AND u.activated=true")
    public Optional<User> findUserWithMatricule(String matricule);

    //update user
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.username=:username, u.codeExploitant=:codeExploitant WHERE u.matricule=:matricule")
    public void updateUser(@Param("username") String username, @Param("codeExploitant") String codeExploitant, 
            @Param("matricule") String matricule);

    //update password
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.password=:password WHERE u.matricule=:matricule")
    public void updatePassword(@Param("password") String password, @Param("matricule") String matricule);

    //update etat
    @Transactional
    @Modifying
    @Query("UPDATE User u set u.activated=:etat WHERE u.matricule=:matricule")
    public void updateEtatActivated(@Param("etat") boolean etat, @Param("matricule") String matricule);

}

the errors generated

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
10:25:40.442 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1429)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run(SparingApplication.java:1215)
at org.bni.gestionoperation.GestionOperationApplication.main(GestionOperationApplication.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService' defined in file [C:\PROJETBNI\ECLIPSE_WORKSPACE\Gestion_Operation\target\classes\org\bni\gestionoperation\service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636)
... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IUser': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778)
... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.bni.gestionoperation.model.User
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582)
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:74)
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:211)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:161)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:144)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:312)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297)
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212)
at org.springframework.data.util.Lazy.get(Lazy.java:94)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:121)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799)
... 48 common frames omitted
How to&Answers:

my datasources are manually generated and I forgot to modify the package in entityScan from the factory.

factory.setPackagesToScan("org.bni.gestionoperation.model");