How does Spring prevent a second call to bar() when using Java based configurations?
I\'m wondering compile time annotation processing or by proxying the method?
Assuming you created your context a little something like
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
Because of @Configuration
, Spring will create a bean of type AppConfig
and proxy it because it has @Bean
methods. You should check out ConfigurationClassEnhancer
for implementation details.
These methods aren't called on the object directly. Obviously they can't since they aren't known at compile time. They are called through reflection on the proxy.
So when you have
@Bean
public CustomBean foo() {
return new CustomBean(bar());
}
which is equivalent to
@Bean
public CustomBean foo() {
return new CustomBean(this.bar());
}
the this
is referring to a proxy which caches the result of the method invocation and returns it immediately if it's called it before.