</bean>
</beans>
As you can see, not only have we configured the two MessageDigestFactoryBeans, but we have also
configured a MessageDigester, using the two MessageDigestFactoryBeans, to provide values for the
digest1 and digest2 properties. For the defaultDigest bean, since the algorithmName property was not
specified, no injection will happen, and the default algorithm (i.e., MD5) that was coded in the class will
be used. In Listing 5-22, you see a basic example class that retrieves the MessageDigester bean from the
BeanFactory and creates the digest of a simple message.
Listing 5-22. Using MessageDigester
package com.apress.prospring3.ch5.factory;
import org.springframework.context.support.GenericXmlApplicationContext;
public class MessageDigestExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:factory/factory.xml");
ctx.refresh();
MessageDigester digester = (MessageDigester) ctx.getBean("digester");
digester.digest("Hello World!");
}
}
Running this example gives the following output:
Using digest1
Using alogrithm: SHA1
[B@786c730
Using digest2
Using alogrithm: MD5
[B@217f242c
As you can see, the MessageDigest bean is provided with two MessageDigest implementations, SHA1
and MD5, despite that no MessageDigest beans are configured in the BeanFactory. This is the
FactoryBean at work.
FactoryBeans are the perfect solution when you are working with classes that cannot be created
using the new operator. If you work with objects that are created using a factory method and you want to
use these classes in a Spring application, then create a FactoryBean to act as an adaptor, allowing your
classes to take full advantage of Spring's IoC capabilities.
Accessing a FactoryBean Directly
Given that Spring automatically satisfies any references to a FactoryBean by the objects produced by that
FactoryBean, you may be wondering whether you can actually access the FactoryBean directly. The
answer is "yes."
Accessing the FactoryBean is actually very simple: you simply prefix the bean name with an
ampersand in the call to getBean(), as shown in Listing 5-23.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home