10.5. Decoupling Your Application from External Services
Problem
You want to decouple your Struts application from a specific implementation of an external business service.
Solution
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 ...
Get Jakarta Struts Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.