Вызвано: org.springframework.beans.factory.NoSuchBeanDefinitionException: нет подходящего bean-компонента типа - PullRequest
2 голосов
/ 06 мая 2020

У меня проблема, с которой я не могу справиться самостоятельно. Я перепробовал все, что можно (на мой взгляд). Мне действительно нужна ваша помощь, потому что у меня нет никаких идей.

У меня такая ошибка:

...
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'web.repositories.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

...

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'web.repositories.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

...

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'web.repositories.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

...

Мой код:

interface UserRepository

@Repository
public interface UserRepository  extends JpaRepository<User, Long> {

    User findByUsername(String username);
}

класс UserService

@Service("userService")
public class UserService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

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

        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        return user;
    }

    public User findUserById(Long userId) {
        Optional<User> userFromDb = userRepository.findById(userId);
        return userFromDb.orElse(new User());
    }

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

класс SecurityConfig

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "web")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("userService")
UserService userService;

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login")
                .successHandler(new LoginSuccessHandler())
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll();

        http.logout()
                .permitAll()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout")
                .and().csrf().disable();

        http
                .authorizeRequests()
                .antMatchers("/login").anonymous()
                .antMatchers("/admin_panel")
                .access("hasAnyRole('ADMIN')")
                .anyRequest()
                .authenticated()
        ;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

Моя папка иерархия:

enter image description here

Помогите пожалуйста ... Несколько дней пытаюсь создать CRUD-приложение Spring Security. Я запутался. Я не могу исправить эту ошибку.

1 Ответ

2 голосов
/ 06 мая 2020

Вы должны включить конфигурацию JpaRepositories, добавить аннотацию @EnableJpaRepositories к вашей конфигурации

@Configuration
@EnableJpaRepositories("web.repositories")
public class ApplicationConfiguration {

   @Bean  public EntityManagerFactory entityManagerFactory() {
     // put here your favourite entity manager factory
   }
}

надеюсь, что это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...