need to code the setup yourself. All of the examples in this chapter require manual setup of the
BeanFactory implementation.
Although a BeanFactory can be configured programmatically, it is more common to see it
configured externally using some kind of configuration file. Internally, bean configuration is represented
by instances of classes that implement the BeanDefinition interface. The bean configuration stores not
only information about a bean itself but also about the beans that it depends on. For any BeanFactory
implementation classes that also implement the BeanDefinitionRegistry interface, you can read the
BeanDefinition data from a configuration file, using either PropertiesBeanDefinitionReader or
XmlBeanDefinitionReader. The two main BeanFactory implementations that come with Spring
implement BeanDefinitionRegistry. The PropertiesBeanDefinitionReader reads the bean definition
from properties files, while XmlBeanDefinitionReader reads from XML files.
So you can identify your beans within the BeanFactory, each bean can be assigned either an ID or a
name, or both. A bean can also be instantiated without any ID and name (known as an anonymous
bean) or as an inner bean within a specific bean. Each bean has at least one name but can have any
number (additional names are separated by commas). Any names after the first are considered aliases
for the same bean. You use bean IDs or names to retrieve a bean from the BeanFactory and also to
establish dependency relationships--that is, bean X depends on bean Y.
BeanFactory Implementations
The description of the BeanFactory might make using it seem overly complex, but in practice, this is not
the case. Take a look at a simple example.
Let's say you have an implementation that mimics an oracle that can tell you the meaning of life.
Listings 4-10 and 4-11 define the interface and a simple implementation, respectively.
Listing 4-10. The Oracle Interface
package com.apress.prospring3.ch4;
public interface Oracle {
public String defineMeaningOfLife();
}
Listing 4-11. A Simple Oracle Interface Implementation
package com.apress.prospring3.ch4;
public class BookwormOracle implements Oracle {
public String defineMeaningOfLife() {
return "Encyclopedias are a waste of money - use the Internet";
}
}
Now let's see, in a stand-alone Java program, how we can initialize Spring's BeanFactory and obtain
the oracle bean for processing (see Listing 4-12).
Listing 4-12. Using the Bean Factory
package com.apress.prospring3.ch4;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home