Java Reference
In-Depth Information
7.5. Groovy with JavaConfig
Spring introduced a third way to configure beans in version 3.0. Originally all beans were
configured using XML. Then version 2.0 introduced annotations (assuming JDK 1.5 is
available)like @Component , @Service ,and @Repository andcomponentscansthat
picked them up.
In version 3.0 Spring introduced a Java configuration option. Instead of defining all your
beans in a central location in XML, or spreading annotations throughout the code base in
Java, now you can define the beans in a Java class annotated with @Configuration .
Inside the configuration file, individual beans are annotated with @Bean .
One of the advantages of this approach is that the configuration information is strongly
typed, because it's all written in Java. Another advantage, though, is that you're now free
to write whatever code you want, as long as you ultimately return the proper object.
Considerthefollowingexample.Intheaccountmanagerexamplediscussedpreviously,say
I want to charge a processing fee once a month. [ 14 ] To do so I create a class that processes
accounts, called, naturally enough, AccountProcessor . I want the Account Pro-
cessor to get all the accounts and charge each one a fee of one dollar. [ 15 ]
14 Gee, I feel more like a real banker already.
15 It's not much, but it's a start.
If I did this in the traditional way, I would inject the AccountDAO into the Accoun-
tProcessor . Then, in a processAccounts method, I would use the DAO to retrieve
the accounts and charge the fee on each. With the Java configuration option, however, I
have an alternative.
The following listing shows the AccountProcessor class, in Java this time.
Listing 7.21. An account processor that debits each account by one dollar
package mjg.spring.services;
import java.util.List;
 
 
Search WWH ::




Custom Search