To assemble a bean, one simply has to use the constructs provided by Java:
@Bean(scope = DefaultScopes.SINGLETON) public Person rod() { return new Person("Rod Johnson"); } @Bean(scope = DefaultScopes.PROTOTYPE) public Book book() { Book book = new Book("Expert One-on-One J2EE Design and Development"); book.setAuthor(rod()); // rod() method is actually a bean reference ! return book; }
In the example above, the book author is using the return value of rod method. However, since both book and rod methods are marked with @Bean, the resulting beans, managed by Spring, will respect the container semantics: rod bean will be a singleton while book bean a prototype. When creating the configuration, Spring is aware of the annotation context and will replaces the rod() method invocation with a reference to the bean named 'rod'.
The container will return a new Book instance (prototype) each time book bean is request but will return the same instance (a singleton) for rod bean.
The code above is equivalent to:
<bean id="rod" class="Person" scope="singleton"> <constructor-arg>Rod Johnson</constructor-arg> </bean> <bean id="book" class="Book" scope="prototype"> <constructor-arg>Expert One-on-One J2EE Design and Development</constructor-arg> <property name="author" ref="rod"/> </bean>
Note that while the examples above used two common scopes types, any type of scoping can be specified:
@Bean (scope = "customer") public Bag shopingBag() { return new Basket(); } @Bean (scope = "shift") public Manager shopManager() { ... }