diff --git a/spring-framework-reference/src/beans.xml b/spring-framework-reference/src/beans.xml index d57474c270..dfbd1074cb 100644 --- a/spring-framework-reference/src/beans.xml +++ b/spring-framework-reference/src/beans.xml @@ -6658,6 +6658,9 @@ public class AppConfig { } + + +
Bean aliasing @@ -6677,6 +6680,66 @@ public class AppConfig { }
+ +
+ Further information about how Java-based configuration works internally + + The following example shows a @Bean annotated method being called twice: + + +@Configuration +public class AppConfig { + + @Bean + public ClientService clientService1() { + ClientServiceImpl clientService = new ClientServiceImpl(); + clientService.setClientDao(clientDao()); + return clientService; + } + @Bean + public ClientService clientService2() { + ClientServiceImpl clientService = new ClientServiceImpl(); + clientService.setClientDao(clientDao()); + return clientService; + } + + @Bean + public ClientDao clientDao() { + return new ClientDaoImpl(); + } +} + + + clientDao() has been called once in clientService1() and once in + clientService2(). + Since this method creates a new instance of ClientDaoImpl and returns it, you would normally expect having 2 instances + (one for each service). + That definitely would be problematic: in Spring, instantiated beans have a singleton scope by default. + This is where the magic comes in: + All @Configuration classes are subclassed at startup-time with CGLIB. In the subclass, the child method checks the container first for any + cached (scoped) beans before it calls the parent method and creates a new instance. + + + + Behaviour could be different according to the scope + of your bean. We are talking here about Singletons. + + + + + There are a few restrictions due to the use of CGLIB to dynamically add features startup-time: + + + Configuration classes should not be final + + + They should have a constructor with no arguments + + + + + +