1. Concept
What is config method in Spring? Any method that is anotated by @autowired is config method.
What’s the difference between a normal method and a config method in spring? Config method will be automatically invoked when the bean instance created, after constructor but before @PostConstruct. The parameters of config method will be autowired from the application context.
The name of the method doen’t matter and parameter number doesn’t matter. In fact we often use @autowired before setter method, that’s just a special case of spring config method.
2. Usage of config method
Genetic config method is not widely use as field injection, setter injection or constructor injection, but config method is used in spring security. According to spring security official reference here, the first step to config spring security is to extend from WebSecurityConfigurerAdapter like below.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.*; import org.springframework.security.config.annotation.authentication.builders.*; import org.springframework.security.config.annotation.web.configuration.*; @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); } }
This is a good example of using config method. config method will be automatically invoked when bean instantiated, that’s why the document said
The name of the configureGlobal method is not important.
Because it just a config method, and will be automatically invoked with a AuthenticatonManagerBuilder bean from context. The purpose of this method is just to using AuthenticationManagerBuilder to setup authentication provider before real logic begins.
0 comments:
Post a Comment