java - 由 : org. springframework.beans.factory.NoSuchBeanDefinitionException 引起:没有合格的 bean 类型

标签 java spring spring-mvc spring-security autowired

我遇到了一个我无法独自解决的问题。我已经尝试了一切可能的方法(在我看来)。我真的需要你的帮助,因为我没有任何想法。

我有这个错误:

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

class 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();
    }
    ...
}

class 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();
    }
}

My folder hierarchy:

enter image description here

请帮忙... 几天来我一直在尝试创建 Spring Security CRUD 应用程序。我很困惑。我无法解决这个错误。

最佳答案

您必须启用 JpaRepositories 配置,将 @EnableJpaRepositories 注释添加到您的配置中

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

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

希望这有帮助

关于java - 由 : org. springframework.beans.factory.NoSuchBeanDefinitionException 引起:没有合格的 bean 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61630137/

相关文章:

java - 在系统 A->B->C 之间发送文件而不将整个文件存储在 B 中

用于引起/包装异常的 Spring ExceptionHandler

java - 如何在 NetBeans VM 选项中指定显示 SplashScreen 的时间?

hibernate - 多模块项目 spring 3.0 AnnotationSessionFactoryBean packagesToScan 属性值按模块设置

java - 在 Spring MVC Controller 中创建的 cookie 上设置 http-only

spring - Spring Integration 中的非阻塞 TCP 连接

java - Spring 有 ORM,还是只使用 ORM 框架?

java - 使用 ArrayList 内部的引用来调用方法,并更改引用对象的当前状态?

java - 如何在esapi中生成Master Key和MasterSalt

java - 使用对称/预共享 key 的安全通信是否发生在普通套接字或 SSLSocket 上是否重要?如何?