Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @bean和@Autowired实际上是如何工作的?_Java_Spring_Spring Bean - Fatal编程技术网

Java @bean和@Autowired实际上是如何工作的?

Java @bean和@Autowired实际上是如何工作的?,java,spring,spring-bean,Java,Spring,Spring Bean,我的配置: @Autowired private PasswordEncoder passwordEncoder; @Bean public PasswordEncoder passwordEncoderBean() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationM

我的配置:

   @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(jwtUserDetailsService)
                .passwordEncoder(passwordEncoder);
    }
这段代码运行良好。但是如果我从
passwordEncoder
中删除
@Autowired
,那么我必须在
configure
方法中添加
@Autowired
。但此规则不适用于
authenticationManagerBean()
方法。有人能解释一下吗?

看看这个URL 在这里,您似乎将Autowire AuthenticationManagerBuilder身份验证为@Bean


配置(AuthenticationManagerBuilder auth),使其在这种情况下工作,并且passwordEncoder也自动连接

您似乎使用了Spring注释配置


如果不向方法或字段添加Spring注释,Spring不知道需要启动它,因此当在Spring上下文中使用时(也没有在Spring外部初始化),对象将为null,出于安全原因,您需要避免以明文形式存储密码。基于这一原则,您可以选择对密码进行编码

在您的示例中,您使用的是PasswordEncoder接口:

.passwordEncoder(passwordEncoder);
使用这种方法,您必须通知一个实现。在Spring中,您可以使用@Autowired(在声明中或类似于使用PasswordEncoder接口的方法上的代码)注入此实现

只是一个问题。。。为什么要创建一个实现

public PasswordEncoder passwordEncoderBean(){...

我认为这种方法可以替代自动连线编码接口。

我认为您应该展示更多的代码,以便更好地回答这个问题。您是否有bean configuration.xml文件?“但此规则不适用于authenticationManagerBean()方法”当然,因为您覆盖了它(不能将PasswordEncoder添加为参数),我不知道使用此方法的确切目标,但您的示例中有两个不同的PasswordEncoder。接口声明(您需要在其中包含@Autowired)和一个返回一个BCryptPasswordEncoder实例(未使用)的方法。您是对的。Spring Boot提供默认的全局AuthenticationManager。所以为什么我需要使用PasswordEncoder自动连线,而不需要AuthenticationManager。