@Bean annotation on a static method

后端 未结 2 1977
一生所求
一生所求 2021-02-09 09:50

Can anyone explain me why a @Bean on a static method is returning 2 different instances ?

I can understand that @Bean on a method non static li

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 10:40

    Because you create a new object for every method call to bbb(). Inter-bean dependencies (if you just call the bean producing method) work in that way, that a proxy is created for your configuration class, and the proxy intercepts method calls to the bean methods to deliver the correct bean (singleton, prototype etc.). However, static methods are not proxied, so when you call the static method, Spring doesn't know about it and you just get the regular Java object. With the PropertySourcesPlaceholderConfigurer it is different, because that method isn't directly called in that class, the bean will only be injected where it is used.

提交回复
热议问题