Java Reference
In-Depth Information
Solution
Spring 3.0 requires Java 5 from the bottom up. Support has been added throughout, from the smaller
convenience methods to methods that will likely be used a lot and whose use of the new features
translates into a lot of saved typing. You will work through the major changes here.
How It Works
There are many changes related to Java 5 that are, in some cases, very relevant for the average user of
Spring 3.0; some are decidedly less so. Some of the changes are mentioned here, and you'll be referred
to a more advanced treatment of the topic in other chapters.
BeanFactory and FactoryBean
The most immediate visible use of generics in Spring 3.0 is apparent when dealing with BeanFactory .
BeanFactory is the super interface for ApplicationContext , which you'll use in almost every application
of Spring, at some level or another. Two methods— getBean() from the BeanFactory interface and
getBeansOfType() from the ListableBeanFactory interface—are now generic-friendly. You can replace a
lot of code with these new methods. The resultant code might be slightly more verbose, but it removes
a lot of ambiguity from the original incantations. After all, incorrect usage could yield a compiler error!
Here you see two calls using the new methods. In the first invocation of getBean() , you specify the
bean's name as the first parameter and the type of the bean as the second, which enables you to avoid a
cast. The second example, getBeansOfType() , demonstrates that the returned Map (whose keys are the
bean names and values the instances of the beans whose interface is castable to Cat ) is parameterized to
a type, which makes iteration more predictable and easier.
import java.util.Map;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class GenericFriendlyLookupExample {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(args[0]);
context.start();
// without generics
Cat catWithoutGenerics = (Cat) context.getBean("fluffy");
// with generics
Cat catWithGenerics = context.getBean("fluffy", Cat.class);
// without generics
Map catsWithoutGenerics = context.getBeansOfType(Cat.class);
// with generics
Map<String, Cat> catsWithGenerics =
context.getBeansOfType( Cat.class);
for(String key : catsWithGenerics.keySet()) {
Cat cat = catsWithGenerics.get( key );
// no need to cast!
}
}
Search WWH ::




Custom Search