首页 > 解决方案 > 运行 SpringBoot jar 文件时出现 BeanCreation 异常

问题描述

我正在使用一些密码编码器和用户帐户创建一个 Spirng 安全应用程序。我在运行 .jar 文件时遇到问题。当我在 IDE 中运行它时,一切都很好。似乎必须在创建 userService 之前完成创建名为 passwordEncoder 的 Bean。我不知道如何执行这样的创作。或者也许我错了,问题是其他的。这是代码:

豆:

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

用户服务

 @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public UserService(UserRepository userRepository,
                       RoleRepository roleRepository,
                       BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

安全配置

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

例外

 Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'instalator': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' defined in URL [jar:file:/home/suchar/Dokumenty/Java%20Training/JDict/target/JDictionary-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/pl/micsoc/dictionary/service/UserService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'bCryptPasswordEncoder'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'passwordEncoder': Requested bean is currently in creation: Is there an unresolvable circular reference?

标签: javaspring-security

解决方案


试试这个UserService

private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
public UserService(UserRepository userRepository,
                   RoleRepository roleRepository,
                   @Lazy BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.userRepository = userRepository;
    this.roleRepository = roleRepository;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

推荐阅读