Spring:通过私有方法注册bean

The*_*ous 2 java spring spring-mvc

我正在配置 spring 安全性,下面是我的代码-

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

@Bean(name="encoder")
public BCryptPasswordEncoder getPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
...
}
Run Code Online (Sandbox Code Playgroud)

一旦我应用了@Autowire-

@Override
@Autowire
    protected void configure(HttpSecurity http) throws Exception {
    ...
    }
Run Code Online (Sandbox Code Playgroud)

这会在容器中引发异常,没有类型为“HttpSecurity”的 bean,这是预期的。

但是当我申请时@Autowire——

@Override
@Autowire
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder);
    }
Run Code Online (Sandbox Code Playgroud)

没有例外?这个AuthenticationManagerBuilder豆子在豆厂里怎么样?

当我用这样的私有方法更改我的 bean 注册时 -

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

@Bean(name="encoder")
private BCryptPasswordEncoder getPasswordEncoder(){
    return new BCryptPasswordEncoder();
}
Run Code Online (Sandbox Code Playgroud)

这是抛出异常,方法不能是私有的。为什么会这样?

Ram*_*nti 6

来自 Spring 文档

通常,@Bean 方法在 @Configuration 类中声明。在这种情况下,bean 方法可以通过直接调用它们来引用同一类中的其他 @Bean 方法。这确保了 bean 之间的引用是强类型和可导航的。这种所谓的“豆间引用”保证尊重范围和 AOP 语义,就像 getBean() 查找一样。这些是从原始“Spring JavaConfig”项目中已知的语义,它们需要在运行时对每个此类配置类进行 CGLIB 子类化。因此,@Configuration 类及其工厂方法在此模式下不得标记为 final 或 private

参考链接