Listing 5-23. Accessing FactoryBeans Directly
package com.apress.prospring3.ch5.factory;
import java.security.MessageDigest;
import org.springframework.context.support.GenericXmlApplicationContext;
public class AccessingFactoryBeans {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:factory/factory.xml");
ctx.refresh();
MessageDigest digest = (MessageDigest) ctx.getBean("shaDigest");
MessageDigestFactoryBean factoryBean =
(MessageDigestFactoryBean) ctx.getBean("&shaDigest");
try {
MessageDigest shaDigest = factoryBean.getObject();
System.out.println(shaDigest.digest("Hello world".getBytes()));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This feature is used in a few places in the Spring code, but your application should really have no
reason to use it. The FactoryBean interface is intended to be used as a piece of supporting infrastructure
to allow you to use more of your application's classes in an IoC setting. Avoid accessing the FactoryBean
directly and then invoking its getObject() manually, and let Spring do it for you; if you do this manually,
you are making extra work for yourself and are unnecessarily coupling your application to a specific
implementation detail that could quite easily change in the future.
Using the factory-bean and factory-method Attributes
Sometimes you need to instantiate JavaBeans that were provided by a non-Spring-powered third-party
application. You don't know how to instantiate that class, but you know that the third-party application
did provide a class that can be used to get an instance of the JavaBean that your Spring application
required. In this case, Spring bean's factory-bean and factory-method attributes in the <bean> tag can
be used.
To take a look at how it works, Listing 5-24 shows another version of the MessageDigestFactory that
provides a method to return a MessageDigest bean.
Listing 5-24. The MessageDigestFactory Class
package com.apress.prospring3.ch5.factory;
import java.security.MessageDigest;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home