Search code examples
javaspring-bootspring-securityjavabeans

How @Bean is used in a class without @Configuration when configuring Spring Security in a Spring Boot app?


I'm learning about Spring Security in a Spring Boot app. I know that you need to use @Bean only in a @Configuration class. But I see this example for configuration Spring Security and the @Bean is used in a class without @Configuration. How is this possible? Thank you!

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests().antMatchers("/authenticate").permitAll()
                .anyRequest().authenticated();
    }

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

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

Solution

  • When you are in a such case, take a look at the documentation, here @Bean documentation you can see that it is not mandatory to use @Bean in a @Configuration class:

    @Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class.

    If you also take a look at @EnableWebSecurity doc you can see that it includes @Configuration.

    EDIT: Hints

    For a Spring Boot application, when we use @EnableWebSecurity we disable security auto-configuration, so it's preferable to simply doing something like this:

    @Configuration
    // @Order(...)   we can set the order of the filter chain
    public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
          // configuration here
    }
    

    In this case we keep the configuration provided by Spring Boot + our own configurations.