首页 > 解决方案 > 谁调用 configureGlobal 函数?如何调用configureGlobal函数?

问题描述

我在学习 Spring Security 时有一个问题。

为了设置AuthenticationManagerBuilder,我使用configureGlobal@Autowired.

我听说configurationGlboal函数名可以是任何东西(甚至是任何东西!)

谁调用configureGlobal函数?如果函数名称可能不同,它如何调用它?

@EnableWebMvc
@Configuration
@ComponentScan({ "com.company.mypackage" })
@EnableWebSecurity
public class SpringWebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user").password("password").roles("USER").and()
          .withUser("admin").password("password").roles("USER", "ADMIN");
    }     
}

标签: spring-bootspring-security

解决方案


Spring 调用该方法,因为它被标记为自动装配,请参阅Autowired

自动装配方法

配置方法可以有任意名称和任意数量的参数;这些参数中的每一个都将与 Spring 容器中的匹配 bean 自动装配。Bean 属性设置方法实际上只是这种通用配置方法的一个特例。这样的配置方法不必是公开的。

但是对于 Spring Security,您还必须注释您的类,请参阅EnableGlobalAuthentication

带有注解的注解EnableGlobalAuthentication也表明被注解的类可用于配置AuthenticationManagerBuilder. 例如:

@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

       @Autowired
       public void configureGlobal(AuthenticationManagerBuilder auth) {
               auth.inMemoryAuthentication().withUser("user").password("password").roles("USER")
                           .and().withUser("admin").password("password").roles("USER", "ADMIN");
       }

       // Possibly overridden methods ...
}

以下注解用EnableGlobalAuthentication

  • EnableWebSecurity
  • EnableWebMvcSecurity
  • EnableGlobalMethodSecurity

在没有注释AuthenticationManagerBuilder的类中进行配置会产生不可预知的结果。EnableGlobalAuthentication


推荐阅读