SPRING IN ACTION 第4版笔记-第二章-004-Bean是否单例

时间:2023-03-08 19:26:25
SPRING IN ACTION 第4版笔记-第二章-004-Bean是否单例

spring的bean默认是单例,加载容器是会被化,spring会拦截其他再次请求bean的操作,返回spring已经创建好的bean.

It appears that the CompactDisc is provided by calling sgtPeppers , but that’s not
exactly true. Because the sgtPeppers() method is annotated with @Bean , Spring will
intercept any calls to it and ensure that the bean produced by that method is returned
rather than allowing it to be invoked again.
For example, suppose you were to introduce another CDPlayer bean that is just
like the first:

@Bean
public CompactDisc sgtPeppers() {
return new SgtPeppers();
} @Bean
public CDPlayer cdPlayer() {
return new CDPlayer(sgtPeppers());
}
@Bean
public CDPlayer anotherCDPlayer() {
return new CDPlayer(sgtPeppers());
}

If the call to sgtPeppers() was treated like any other call to a Java method, then each

CDPlayer would be given its own instance of SgtPeppers . That would make sense if we
were talking about real CD players and compact discs. If you have two CD players,
there’s no physical way for a single compact disc to simultaneously be inserted into
two CD players.
In software, however, there’s no reason you couldn’t inject the same instance of
SgtPeppers into as many other beans as you want. By default, all beans in Spring are
singletons, and there’s no reason you need to create a duplicate instance for the sec-
ond CDPlayer bean. So Spring intercepts the call to sgtPeppers() and makes sure
that what is returned is the Spring bean that was created when Spring itself called
sgtPeppers() to create the CompactDisc bean. Therefore, both CDPlayer beans will
be given the same instance of SgtPeppers