Level 2.2 CBT Course On Advanced Programming With Spring
Level 2.2 CBT Course On Advanced Programming With Spring
"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
Practice
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
1.1
Oct 13 2008
TPG Confidential
Objective
** 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
Agenda
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
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
ORM AOP
Source level metadata AOP infrastructure Hibernate/IBatis/JDO Support
Web
WebApplicationContext Multipart resolver Web utilities
Web MVC
Web MVC Framework Web Views JSP / Velocity PDF / Excel
DAO
Transaction Infrastructure JDBC / DAO Support
Context
Application context UI support / Validation JNDI,EJB support and Remoting mail
Core
Supporting Utilities Bean Container
Oct 13 2008
TPG Confidential
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
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
11
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
12
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
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
14
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
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
16
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
17
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
20
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
21
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
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
23
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
24
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
25
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="org.springframework.jmx.support.MBeanServerConnectionFactory 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
Oct 13 2008
TPG Confidential
27
5.2 MessageSender
Oct 13 2008
TPG Confidential
28
Java 2 Timer
Timer TimerTask
Quartz
Oct 13 2008
TPG Confidential
29
6.2 ScheduledTimerTask
scheduled
<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
30
6.3 TimeFactoryBean
Oct 13 2008
TPG Confidential
31
Oct 13 2008
TPG Confidential
32
Oct 13 2008
TPG Confidential
33
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
34
Oct 13 2008
TPG Confidential
35
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
36
Oct 13 2008
TPG Confidential
37
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
38
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
39
Business Services Layer:Exposes key functionality. Manages transaction boundaries,includes business logic.No knowledge of persistence specifics. Declarative services typically used here.
DAO Interface implementing layer Retrieves,Saves entities using ORM tool, JDBC
RDBMS
Oct 13 2008 TPG Confidential 40
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
Advantages
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
42
Summary
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 (http://www.quartzscheduler.org). Applications built using Spring are very easy to test.
Oct 13 2008
TPG Confidential
43
References
Oct 13 2008
TPG Confidential
44
Additional Resources
SL #
1
Topic Element
Accessing and implementing EJBs
Resource Location/Link
http://static.springframework.org/spring/docs/ 1.2.x/reference/ejb.html http://static.springframework.org/spring/docs/ 1.2.x/reference/jmx.html http://static.springframework.org/spring/docs/ 1.2.x/reference/mail.html http://static.springframework.org/spring/docs/ 1.2.x/reference/scheduling.html http://static.springframework.org/spring/docs/ 1.2.x/reference/testing.html
Remarks
JMX Support Sending Email with Spring mail abstraction layer Scheduling jobs using Quartz or Timer Testing
3 4 5
Oct 13 2008
TPG Confidential
45