Search code examples
javaspringspring-bootconfigurationannotations

In spring boot config class, why should I use Bean annotation and set the method 'public'?


I'm learning Spring boot + oauth2 + JWT, In the AuthorizationServerConfig.class (or some other config classes), I noticed that in many examples, they use a @Bean annotation to decorate some methods, and set the methods to 'public'. For exmaple:

@Configuration
@EnableAuthorizationServer
@Slf4j
public class AuthorizationServerConfig extends 
AuthorizationServerConfigurerAdapter {
....
....
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(this.accessTokenConverter());
    }
....
}

If I'm removing the Bean annotation and making the method private, my app still works. So my question is, why do we need the Bean annotation and public the method?


Solution

  • In Spring the @Bean annotation is a way (i think the simplest one) to expose to IOC contex a particular object instance. This means that you can "get back" this instance in any other bean using the @Autowired annotation (old but good documentation)

    Spring Boot is a sort of "spring autoconfigurator" that will automatically configure spring context by providing all Beans needed for you application with a general purpose setup. Spring Boot provides the ability to customize your environment through both java classes and properties files. In you case you were customizing the spring context though a java class (with a class annotated with @Configuration) where you were overriding the default spring TokenStore bean with you own instance that in this case was probably an instance semantically equal to the one provided by Spring Boot thats why if you remove the @Bean annotation or you put the "private" keyword to the method the application is working because the same bean is automatically injected into the spring context by spring boot (I'm assuming that there is a class that use your TokenStore throught @Autowire) .

    I hope that this little (and very simplified) explanation helps you to understand how spring boot works :)