February 2005
Intermediate to advanced
528 pages
12h 53m
English
You want to decouple your Struts application from a specific implementation of an external business service.
Create an interface that provides an API for the business service. Then
use a ServiceFactory class like the one shown in
Example 10-13 to provide access to the service.
Example 10-13. Service factory
package com.oreilly.strutsckbk.ch10;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ServiceFactory {
private static Log log = LogFactory.getLog(ServiceFactory.class);
public SecurityService createSecurityService( ) {
SecurityService service = null;
try {
service = (SecurityService)
Class.forName(securityServiceImpl).newInstance( );
} catch (Exception e) {
log.error(
"Unable to create SecurityService for impl:"+
securityServiceImpl);
}
return service;
}
protected void setSecurityServiceImpl(String securityServiceImpl) {
this.securityServiceImpl = securityServiceImpl;
}
private String securityServiceImpl;
}You can use a Struts PlugIn, like the one shown in
Example 10-14, to bind a service implementation to the
interface, and store a reference to the service in the servlet
context.
Example 10-14. Service factory plug-in
package com.oreilly.strutsckbk.ch10; import javax.servlet.ServletException; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; public class ServiceFactoryPlugin implements ...