You are on page 1of 45

Technology Practices Group Java Competency Framework

"Incubate, Nurture and Deploy Technology Experts Innovate, Build and Deliver Technology Solutions

Oct 13 2008

TPG Confidential

Document Details
Business Unit Group BFSI Technology Practices Group

Sub-Practices Initiative

Java Practice
Java CoE technologies Competency Framework

Competency Level
Experience Level Pre-Requisite Version Author Total number of slides Duration of learning

2.2 Level 3
3 Years J2EE 1.1 MuthuVeerappan Krishnamoorthy Baskar Muniyandi 45 24hrs
TPG Confidential 2

Oct 13 2008

Revision History
Version (x.yy) 1.0 Date of Revision September 2007 January 2009 Description of Change Reason for Change Affected Sections Approved By

Initial Version


Content on new templates. Review and updation.

Oct 13 2008

TPG Confidential

** Please read the objective of this content clearly **

This presentation is essentially to set the context of learning on this topic. The content deals with the coverage( both depth and width applicable) for this particular topic in a concise format, providing an overview of the elements that makes up this Topic level. While this content provides with a high level understanding of the topic to the level of depth that is expected at this particular level( Levels 1.1, 2.1 etc ) , it is highly recommended to have a detailed in depth learning using the resources mentioned in the Additional Resources section.

Oct 13 2008

TPG Confidential

Introduction to Spring What is Spring? Spring Components Overview of Spring Components Integrating with other web frameworks Accessing and Implementing EJBs JMX Support Sending Email with Spring Scheduling Jobs using Quartz or Timer Exception Handling Testing Features of Spring Framework Architectural Layers in a typical Spring Application Advantages Summary

Oct 13 2008

TPG Confidential

1.1 What is Spring?

A J2EE Framework designed to make building applications easier. Provides a means to manage your business objects and their dependencies. Inversion of Control allows classes to be loosely coupled and dependencies written in XML. Spring is a Lightweight Application Framework. Where Struts, WebWork and others can be considered Web frameworks, Spring addresses all tiers of an application.

Oct 13 2008

TPG Confidential

1.2 Spring Components

Source level metadata AOP infrastructure Hibernate/IBatis/JDO Support

WebApplicationContext Multipart resolver Web utilities

Web MVC Framework Web Views JSP / Velocity PDF / Excel

Transaction Infrastructure JDBC / DAO Support

Application context UI support / Validation JNDI,EJB support and Remoting mail

Supporting Utilities Bean Container

Oct 13 2008

TPG Confidential

1.3 Overview of Spring Components

Core + Context = Framework IoC bean container Application context, message sources, resource loading, wiring infrastructure. DAO JDBC Templates taking care of connections, statements, exceptions. DataAccessException Hierarchy. Transaction Infrastructure Programmatic Declarative through IoC & AOP Pluggable strategies (e.g. JDBC, JTA, JDO) ORM Extends DAO, integrates O/R Mapper with Spring concepts Transaction SPI Templates Factories Hibernate, JDO, OJB, iBATIS
Oct 13 2008 TPG Confidential 8

1.3 Overview of Spring Components (Cont..)

AOP Method Interception Adding functionality before, after and around a method call or in case of an exception Introduction Adding methods or fields to an existing class or interface Useful for declarative enterprise services Transaction management Security Thread management Tracing, auditing, notification Web Web application context Binding & validation and web utilities Multipart resolver for file upload Supports Struts, JSF, WebWorks, Tapestry, Web MVC Springs IoC web framework Generic DispatcherServlet and controller Designed for any view technology (JSP, JSTL ) Theme support (CSS/Images/HTML bundles)
Oct 13 2008 TPG Confidential 9

2.1 Integrating with Other Frameworks

Spring can be easily integrated into any Java-based web framework like JavaServer Faces Struts Tapestry WebWork Spring integrates nicely with other web frameworks with two methodologies: Look up Spring beans within Controllers/Actions via the convenience static method: WebApplicationContextUtils.getWebApplicationContext(servletContext). getBean(beanName) Configure the Controllers/Actions for the web framework in a Spring BeanFactory and then use Spring provided proxies in the actual web framework configuration When available, this methodology is preferred This approach lets you design your Controllers/Actions with dependency injection and makes your Controller/Actions more testable
TPG Confidential 10

Oct 13 2008

2.1 Integrating with other web frameworks

All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation <context-param> to set which context files to load.

The <context-param>:

<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml </paramvalue> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>

The <listener>:

If you don't specify the contextConfigLocation context parameter, the ContextLoaderListener will look for a /WEB-INF/applicationContext.xml file to load. Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definitions and puts it into the ServletContext.

Oct 13 2008

TPG Confidential


2.2 Web Integration - JSF

The easiest way to integrate your Spring middle-tier with your JSF web layer is to use the DelegatingVariableResolver
<faces-config> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> <locale-config> <default-locale>en</default-locale> <supported-locale>en</supported-locale> <supported-locale>es</supported-locale> </locale-config> <message-bundle>messages</message-bundle> </application> .. </faces-config>

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's root WebApplicationContext. This allows you to easily inject dependencies into your JSF-managed beans.

Oct 13 2008

TPG Confidential


2.3 Web Integration - Struts

To integrate your Struts application with Spring, you have two options: Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file. <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/action-servlet.xml.xml,/WEB-INF/applicationContext.xml"/> </plug-in>

Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method. public class UserAction extends DispatchActionSupport { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { .. WebApplicationContext ctx = getWebApplicationContext(); UserManager mgr = (UserManager) ctx.getBean("userManager"); // talk to manager for business logic return mapping.findForward("success");

Oct 13 2008 TPG Confidential 13

3.1 Accessing & Implementing EJB

EJB Access

With EJBs it is usual to have A ServiceLocator Takes care of JNDI, initial context, EJB home lookup A Business Delegate Reducing coupling, hides the implementation
Spring approach is to allow the creation and use of proxy objects, normally configured inside a Spring ApplicationContext or BeanFactory, which act as code-less business delegates.

Spring Access

You do not need to write another Service Locator, another JNDI lookup, or duplicate methods in a hand-coded Business Delegate
unless youre adding real value.

Oct 13 2008

TPG Confidential


3.2 Accessing a Local SLSB (StateLess Session Beans)

To obtain the controller object out of a Spring ApplicationContext or BeanFactory, configure a LocalStatelessSessionProxyFactoryBean instance, which will be EJB proxy object. To use a Local, Stateless, Session bean, the spring config entry would be
<bean id="myComponent class=com.ejb.access.LocalStatelessSessionProxyFactoryBean"> <property name="jndiName value=myComponent /> <property name="businessInterface value=com.mycom.MyComponent /> </bean> <bean id="myController" class="com.mycom.myController"> <property name="myComponent" ref="myComponent"/> </bean>

The myComponent bean definition creates a proxy for the EJB, which implements the business method interface. The EJB local home is cached on startup, so theres only a single JNDI lookup. You can swap the bean implementation with a POJO or mock objects without changing the client code. You dont have to write a single line of JNDI lookup or other EJB plumbing code as part of the application.
Oct 13 2008 TPG Confidential 15

3.3 Accessing a Remote SLSB

Accessing remote EJBs is essentially identical to accessing local EJBs, except that the SimpleRemoteStatelessSessionProxyFactoryBean is used. To use a Remote, Stateless, Session bean

<bean id="myComponent" class="...SimpleRemoteStatelessSessionProxyFactoryBean"> <property name="jndiEnvironment"> <ref bean="myEnvironment"/> </property> <property name="jndiName"> <value>myComponent</value> </property> <property name="businessInterface"> <value>com.mycom.MyComponent</value> </property> </bean>

Oct 13 2008

TPG Confidential


3.4 EJB Implementation classes

To implement a Stateless or Stateful session bean, or Message Driven bean, you derive your implementation class from AbstractStatelessSessionBean, AbstractStatefulSessionBean, and AbstractMessageDrivenBean/AbstractJmsMessageDrivenBean, respectively. AbstractEnterpriseBean

Loads a BeanFactory EJB environment variable ejb/BeanFactroyPath specifies the location on the classpath of an XML bean factory definition E.g. /com/mycom/mypackage/mybeans.xml Default bean factory is XmlApplicationContext Applications should use the EJB only as a facade Business logic deferred to beans in BeanFactory

Oct 13 2008

TPG Confidential


3.4.1 Implementing a SLSB

Stateless Session Beans Extend AbstractStatelessSessionBean Save the session context Empty implementation of ejbRemove() ejbCreate() method Throws exception in ejbActivate() and ejbPassivate() Subclasses must implement onEjbCreate() Example class MySlsb extends AbstractStatelessSessionBean { protected void onEjbCreate() throws CreateException { ... } public void businessMethod() { BeanFactory bf = getBeanFactory(); MyBusinessBean mbb = bf.getBean("myBusinessBean"); ... } }

Oct 13 2008 TPG Confidential 18

3.4.2 Implementing a SFSB

Stateful Session Beans Extend AbstractStatefulSessionBean Save the session context Empty implementation of ejbRemove() ejbCreate() method Subclasses must implement onEjbCreate(), ejbActivate() and ejbPassivate() Example class MySfsb extends AbstractStatefulSessionBean { public void ejbCreate() throws CreateException { loadBeanFactory(); ... } public void ejbActivate() { . } public void ejbPassivate() { . } public void businessMethod() { BeanFactory bf = getBeanFactory(); MyBusinessBean mbb = bf.getBean("myBusinessBean"); ... } }

Oct 13 2008 TPG Confidential 19

3.4.3 Implementing a MDB

Example class MyMdb extends AbstractJmsMessageDrivenBean { protected void onEjbCreate() throws CreateException { ... } public void onMessage(Message message) { BeanFactory bf = getBeanFactory(); MyBusinessBean mbb = bf.getBean("myBusinessBean"); ... } }

Oct 13 2008

TPG Confidential


4.1 Spring JMX Support

Automatic registration of any Spring bean as a JMX MBean Flexible control of the management interface Flexible control of Object Names Declarative exposure of MBeans over remote, JSR-160 connectors Proxying of both local and remote MBeans Control of MBean registration behavior (Spring 2.0) Notification support (Spring 2.0)

Oct 13 2008

TPG Confidential


4.2 Exporting your Beans to JMX

Core class MBeanExporter: Registers Spring beans as JMX MBeans with the JMX MBeanServer. Explicit registration of any Spring bean: Valid JMX MBeans POJOs Automatic detection / registration of valid JMX MBeans.

Example <beans> <bean id="exporter class="org.springframework.jmx.export.MBeanExporter"> <property name="beans"> <map> <entry key="bean:name=testBean1" value-ref="testBean"/> </map> </property> </bean> <bean id="testBean" class="org.springframework.jmx.JmxTestBean"> <property name="name" value="TEST"/> <property name="age" value="100"/> </bean> </beans>
Oct 13 2008 TPG Confidential 22

4.3 Automatic Registration

MBeans can be automatically detected by the MBeanExporter by setting the autodetect property to true <bean id="exporter" class="org.springframework.jmx.export.MBeanExporter"> <property name="autodetect" value="true"/> </bean> <bean name="spring:mbean=true class="org.springframework.jmx.export.TestDynamicMBean"/> Here, the bean called spring:mbean=true is already a valid JMX MBean and will be automatically registered by Spring.

Oct 13 2008

TPG Confidential


4.4 Management Interface Control

Powerful and comprehensive facilities Many ways to control the exposed interface MBeanExporter delegates to implementations of MBeanInfoAssembler for creating management interfaces at runtime. Reflection-based (default, exposes everything) Source Level Annotationbased Commons Attributes JDK 5.0 Annotations Java Interface-based Method name-based

Oct 13 2008

TPG Confidential


4.5 Object Name Control

Many ways to control ObjectNames as well MBeanExporter delegates to implementations of ObjectNamingStrategy for creating ObjectNames Based on key from beans property map (default) Based on external Properties file Based on JVMs notion of object identity Based on source-level annotation

Oct 13 2008

TPG Confidential


4.6 JSR 160 Connectors / Proxies

Spring JMX supports creating both server and client Connector beans. A client Connector bean could point to any remote MBeanServer Spring can proxy remote objects: <bean id="clientConnector" class=" Bean> <property name="serviceUrl" value="service:jmx:rmi://remotehost:9875"/> </bean> <bean id="proxy" class="org.springframework.jmx.access.MBeanProxyFactoryBean"> <property name="objectName" value="bean:name=testBean"/> <property name="proxyInterface" value="org.springframework.jmx.IJmxTestBean"/> <property name="server" ref="clientConnector"/> </bean>
Oct 13 2008 TPG Confidential 26

5.1 Sending Email with Spring

SimpleMailMessage - Creating a message

SimpleMailMessage msg = new SimpleMailMessage(); msg.setFrom(""); msg.setTo(""); msg.setCc(new String[] {"", ""}); msg.setBcc(new String[] {"", ""}); msg.setSubject("my subject"); msg.setText("my text");

Oct 13 2008

TPG Confidential


5.2 MessageSender

Defining a message sender

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host"><value></value></property> <property name="username"><value>joe</value></property> <property name="password"><value>abc123</value></property> </bean>

Sending the message

MailSender sender = (MailSender) ctx.getBean("mailSender"); sender.send(msg);

Oct 13 2008

TPG Confidential


6.1 Scheduling Jobs using Quartz or Timer

Built-in support for

Java 2 Timer

Timer TimerTask


Schedulers JobDetails Triggers

Oct 13 2008

TPG Confidential


6.2 ScheduledTimerTask

The task that we want to run

public class MyTask extends TimerTask { public void run() { // do something } Java bean that wraps a } java.util.TimerTask


<bean id="myTask" class="...scheduling.timer.ScheduledTimerTask"> <property name="timerTask"> <bean class="eg.MyTask"/> </property> <property name="delay"><value>60000</value></property> <property name="period"><value>1000</value></property> </bean>

Oct 13 2008

TPG Confidential


6.3 TimeFactoryBean

Creating the scheduler

<bean id="scheduler" class="...scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list><ref bean="myTask"/></list> </property> Creates a java.util.Timer object </bean>

The Timer starts at bean creation time

Oct 13 2008

TPG Confidential


7.1 Exception Handling

In general you want to allow fatal exceptions to propagate up the stack. These exceptions can be handled by a last ditch handler Log the error Notify an administrator Display a friendly error-page for the user. Use an implementation of the HandlerExceptionResolver interface

Oct 13 2008

TPG Confidential


7.2 HandlerExceptionResolver interface

public interface HandlerExceptionResolver { ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex); }

Oct 13 2008

TPG Confidential


7.3 Configuring the HandlerExceptionResolver

Special bean, resolved by type Single implementation out of the box SimpleMappingExceptionResolver Map Exception types to view names Puts the Exception into the model automatically. Useful out of the box, even better for extension

Oct 13 2008

TPG Confidential


7.4 Configuring SimpleMappingExceptionResolver

<bean id="exceptionHandler" class="...SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <value> java.lang.Exception=error </value> </property> </bean>

All exceptions are mapped to the error view

Oct 13 2008

TPG Confidential


7.5 Extending SimpleMappingExceptionResolver

Rather than build your own HandlerExceptionResolver extend the SimpleMappingExceptionResolver Simple process

Override the resolveException() method Call super.resolveException() Perform custom processing Return (potentially modified) ModelAndView

Oct 13 2008

TPG Confidential


8.1 Spring and Testing

Easier test driven development (TDD) Unit testing Allows you to test outside the container without using the Spring container. Integration testing Can use a standalone Spring configuration with mock objects for testing. Consider XMLApplicationContext or FileSystemApplicationContext. Correct wiring of your Spring contexts. Data access using JDBC or ORM tool--correctness of SQL statements. For example, you can test your DAO implementation classes Easy to test POJOs

Oct 13 2008

TPG Confidential


8.2 Testing outside the container

Spring MVC is easy to test outside the container Support classes in spring-mock.jar MockHttpServletRequest MockHttpServletResponse Unit testing Use EasyMock/JMock Test exception handling Test ModelAndView creation Integration testing Extend AbstractTransactionalDataSourceSpringContextTests Use real service/data tier objects

Oct 13 2008

TPG Confidential


9.1 Features of Spring Framework

Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS. AOP Framework: Spring is best AOP framework MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.

Oct 13 2008

TPG Confidential


10.1 Architectural Layers in a typical Spring Application

JSPs or other views Generate HTML Web tier actions Process user input Call Service layer, choose view to display, Remote service exporters: Web services or other protocols

Business Services Layer:Exposes key functionality. Manages transaction boundaries,includes business logic.No knowledge of persistence specifics. Declarative services typically used here.

DAO interface layer Defines persistence operations, independent of implementing technology

O/R Mapping layer J D B C

Persistent domain object (entity) Core OO Model

DAO Interface implementing layer Retrieves,Saves entities using ORM tool, JDBC

Oct 13 2008 TPG Confidential 40

10.1 Architectural Layers in a typical Spring Application

Presentation Layer:This is most likely to be a web tier. It should be possible to have alternative presentation layers-such as a web tier or remote web services faade-on a single, well-designed middle tier. Business Services Layer: This is responsible for transactional boundaries and providing an entry point for operations on the system as a whole. This layer should have no knowledge of presentation concerns, and should be reusable. DAO interface Layer: This is a layer of interfaces independent of any data access technology that is used to find and persist persistent objects. This layer effectively consists of strategy interfaces for the business services layer. This layer should not contain business logic. Implementations of these interfaces will normally use an O/R Mapping technology or Springs JDBC abstraction. Persistent domain objects: These model real objects or concepts such as a bank account. Databases and legacy systems: By far the most common case is a single RDBMS.However,there may be multiple databases, or mix of databases and other transactional or non-transactional legacy systems or other enterprise resources.
Oct 13 2008 TPG Confidential 41


Spring is an application frame work. Unlike single tier frameworks such as struts or Hibernate, Spring aims to help structure whole applications in a consistent, productive manner, pulling together bestof-breed single tier frameworks to create a coherent architecture. Spring enables you to enjoy the key benefits of J2EE, while minimizing the complexity encountered by application code. The essence of spring is in providing enterprise services to Plain Old Java Objects(POJOs).This is particularly variable in a J2EE environment, but application code delivered as POJOs is naturally in a variety of runtime environments. Spring is both the most popular and most ambitious of the lightweight frameworks. It is the only one to address all architectural tiers of a typical J2EE application, and the only one to offer a comprehensive range of services, as well as a lightweight container.

Oct 13 2008

TPG Confidential



Spring integrates existing good solutions and does not compete with them Spring makes it much easier to access EJBs and implement EJBs and functionality within them. The JMX support in Spring provides you with the features to easily and transparently integrate your Spring application into a JMX infrastructure. Spring provides a higher level of abstraction for sending electronic mail which shields the user from the specifics of underlying mailing system and is responsible for a low level resource handling on behalf of the client. Spring supports the Timer, part of the JDK since 1.3, and the Quartz Scheduler ( Applications built using Spring are very easy to test.

Oct 13 2008

TPG Confidential


References Spring Framework Documentation

Oct 13 2008

TPG Confidential


Additional Resources

SL #

Topic Element
Accessing and implementing EJBs

Resource Location/Link 1.2.x/reference/ejb.html 1.2.x/reference/jmx.html 1.2.x/reference/mail.html 1.2.x/reference/scheduling.html 1.2.x/reference/testing.html


JMX Support Sending Email with Spring mail abstraction layer Scheduling jobs using Quartz or Timer Testing

3 4 5

Oct 13 2008

TPG Confidential