This question already has an answer here:
What is a NoSuchBeanDefinitionException and how do I fix it?
                                
                                    (1个答案)
                                
                        
                2年前关闭。
            
        

org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder未被注入。无法找出原因。经历了stackoverflow内部和外部的几个问题,每次都会优化我的searchquery,只是希望找到任何人发布的类似问题。

在调试模式下运行项目时,在上下文初始化期间遇到异常,然后在下面打印出:

Application failed to start due to an exception
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' available: expected at least 1 bean which qualifies as autowire candidate.

Description:

Field encoder in com.codingethics.flightreservation.controller.UserController required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.


该错误在其消息中非常明显,但令人困惑,因为我已经使UserController类和字段编码器都可以使用所需的注释进行自动装配。而且,在这里,我试图注入Spring提供的依赖关系,而不是用户定义的依赖关系。我不确定是否需要其他配置。在同一项目中,我以类似的方式成功使用了JavaMailSender。

那么,令我困扰的是为什么这样做有效? :

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender javaMailSender;

}


但这不是:UserController.java

    @Controller
    public class UserController {

        @Autowired
        private BCryptPasswordEncoder encoder;

}


任何帮助/指导都将受到高度赞赏。

最佳答案

您是否尝试过在@Configuration类中手动创建BCryptPasswordEncoder bean?

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


也许值得尝试一下。

07-24 18:26