I am wondering how spring injection handles calling methods using annotation @Bean. If I put the annotation @Beanin the method and return the instance, I understand that it tells spring to create a bean by calling the method and getting the returned instance. However, sometimes a bean should be used to connect different beans or install different code. This is usually done to invoke the annotated method @Beanto get the instance. My question is why does this not cause multiple instances of bean to float around?
For example, see the code below (taken from another question). The method is entryPoint()annotated with @Bean, so I would suggest that spring will create a new instance BasicAuthenticationEntryPointas a bean. Then we call entryPoint()again in the configure block, but it seems to entryPoint()return an instance of bean and is not called several times (I tried to keep a log and received only one entry in the log). Potentially, we could call entryPoint()several times in other parts of the configuration, and we will always have the same instance. How do I get it right? Does spring magically rewrite methods annotated with @Bean?
@Bean
public BasicAuthenticationEntryPoint entryPoint() {
BasicAuthenticationEntryPoint basicAuthEntryPoint = new BasicAuthenticationEntryPoint();
basicAuthEntryPoint.setRealmName("My Realm");
return basicAuthEntryPoint;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(entryPoint())
.and()
.authorizeUrls()
.anyRequest().authenticated()
.and()
.httpBasic();
}
source
share