Java 无法找到“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”类型的bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51234536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:01:52  来源:igfitidea点击:

a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found

javaspring-bootspring-security

提问by M. Aktas

I want to use Spring Boot Security in my project by creating a simple login screen but i get these error even i define a bean for BCryptPassworrdEncoder. The full error is

我想通过创建一个简单的登录屏幕在我的项目中使用 Spring Boot Security,但是即使我为 BCryptPasswordEncoder 定义了一个 bean,我也会收到这些错误。完整的错误是

Field bCryptPasswordEncoder in com.mahmut.demoemployee.application.dao.Imp.UserDaoImp required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.

com.mahmut.demoemployee.application.dao.Imp.UserDaoImp 中的字段 bCryptPasswordEncoder 需要一个无法找到的“org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”类型的 bean。

Here is my codes.

这是我的代码。

package com.mahmut.demoemployee.application.dao.Imp;
    //Some imports

            @Component
        public class UserDaoImp implements UserDao {

            @Autowired
            UserRepository userRepository;

            @Qualifier("roleRepository")
            @Autowired
            RoleRepository roleRepository;

            @Autowired
            private BCryptPasswordEncoder bCryptPasswordEncoder;

            @Override
            public User save(User user) {
                user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
                user.setActive(1);
                Role userRole = roleRepository.findByRole("ADMIN");
                user.setRoles(new HashSet<Role>(Arrays.asList(userRole)));
                return userRepository.save(user);
            }

            @Override
            public User findUserByEmail(String email) {
                return userRepository.findByEmail(email);
            }

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

And here is my config classes.

这是我的配置类。

    package com.mahmut.demoemployee.application.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
public class WebMvcConfig extends WebSecurityConfigurerAdapter {

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

}

Security Config class

安全配置类

 package com.mahmut.demoemployee.application.config;
//Lots of import here

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;



    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.
                jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.
                authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/registration").permitAll()
                .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/login").failureUrl("/login?error=true")
                .defaultSuccessUrl("/admin/home")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }

}

What i tried is;

我试过的是;

I tried to use PasswordEncoderinstead of BCryptPasswordEncodergives the same error with Password Encoder. I remove the @Componentannotation and write @Serviceit gives same error as well. I dont know if its necessary but here is my pom.xml file. There are only essential dependencies.

我尝试使用PasswordEncoder而不是BCryptPasswordEncoder使用密码编码器给出相同的错误。我删除了@Component注释并写入@Service它也给出了相同的错误。我不知道是否有必要,但这是我的 pom.xml 文件。只有必要的依赖关系。

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mahmut</groupId>
    <artifactId>demo-employee</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo-employee</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

I dont know what else i could do. I checked lots of websites with similiar errors and did them but result is same.

我不知道我还能做什么。我检查了很多有类似错误的网站并做了,但结果是一样的。

采纳答案by GolamMazid Sajib

You used multiple class which extends of WebSecurityConfigurerAdapter. Set orderon WebMvcConfig class.

您使用了多个扩展WebSecurityConfigurerAdapter 的类。order在 WebMvcConfig 类上设置。

@Configuration
@Order(1)
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }
}