SKILLWISE-SPRING
FRAMEWORK
2
Contents
 Recap of earlier session’s points
 Spring AOP
 Spring Mock Testing
 Spring ORM (With Hibernate)
 Spring Scheduler
 Spring JMS
 Spring Email
 Spring Batch
 Spring MVC
 Spring in Real World
 Quick Recap
 References
 Questions?
3
Recap of Earlier Session’s Points
 What is Spring framework?
 IOC and Dependency Injection
 Different types of Injection
 Bean Factory and Beans
 Wiring
 Bean Post Processor
 Plumbing of Code
 Program to Interfaces
4
Spring AOP
 AOP complements OOP
 The key unit of modularity in OOP is the class, whereas
in AOP the unit of modularity is the aspect
 crosscutting concerns
Audit
Authentication
Logging
Transaction Support
5
Spring AOP concepts
 Aspect
 Advice
 Join Point
 Point cut
 Target Object
 AOP Proxy
 Weaving
6
Types of Advices
 Before Advice - (Advice that executes before a join point, but which does not have the
ability to prevent execution flow proceeding to the join point unless it throws an exception)
 After returning advice – (Advice to be executed after a join point completes
normally: for example, if a method returns without throwing an exception)
 After throwing advice – (Advice to be executed if a method exits by throwing an
exception)
 After advice – (Advice to be executed regardless of the means by which a join point exits
normal or exceptional return)
7
Point cuts
 All setter methods
 All methods returning void
 All methods in a package
 All methods with only one parameter
 With Regular Expression
 Programmable point cut model
8
AOP Proxy
 Spring AOP defaults to using standard J2SE dynamic
proxies for AOP proxies
 This enables any interface (or set of interfaces) to be
proxied.
 AspectJ Support
 How to enable AspectJ Support
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
9
Various PointCut Definitions
• execution - for matching method execution join points, this is the primary pointcut designator
used when working with Spring AOP
• within - limits matching to join points within certain types (simply the execution of a method
declared within a matching type when using Spring AOP)
• this - limits matching to join points (the execution of methods when using Spring AOP) where the
bean reference (Spring AOP proxy) is an instance of the given type
• target - limits matching to join points (the execution of methods when using Spring AOP) where
the target object (application object being proxied) is an instance of the given type
• args - limits matching to join points (the execution of methods when using Spring AOP) where the
arguments are instances of the given types
10
Pointcut Example
•@Aspect
•public class SystemArchitecture {
• /**
• * A join point is in the web layer if the method is defined in a type in the com.xyz.someapp.web package or any sub-package under that.
• */
• @Pointcut("within(com.xyz.someapp.web..*)")
• public void inWebLayer() {}
• /**
• * A join point is in the service layer if the method is defined in a type in the com.xyz.someapp.service package or any sub-package under
that.
• */
• @Pointcut("within(com.xyz.someapp.service..*)")
• public void inServiceLayer() {}
• /**
• * A join point is in the data access layer if the method is defined in a type in the com.xyz.someapp.dao package or any sub-package under
that.
• */
• @Pointcut("within(com.xyz.someapp.dao..*)")
• public void inDataAccessLayer() {}
• /**
• * A business service is the execution of any method defined on a service interface. *
• */
• @Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
• public void businessService() {}
•
• /**
• * A data access operation is the execution of any method defined on a dao interface. This definition assumes that interfaces are placed in
the
• * "dao" package, and that implementation types are in sub-packages.
• */
• @Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
• public void dataAccessOperation() {}
•}
11
Advisor
<aop:config>
<aop:advisor
pointcut="com.xyz.someapp.SystemArchitecture.business
Service()"
advice-ref="tx-advice"/>
</aop:config>
<tx:advice id="tx-advice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
12
Spring Mock Testing
 What is a Mock object?
 Different providers of Mock objects
 Mock Objects
 EasyMock
 JMock
 Web - org.springframework.mock.web
 MockHttpServletRequest
 MockHttpServletResponse
 MockHttpSession
 JNDI - org.springframework.mock.jndi
 General Utilities - org.springframework.test.util
13
Spring Mock Testing
public void final testDetails throws Exception {
MyController myController = new MyController();
myController.setDetailsView("detailsName");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setMethod("POST");
request.addParameter("viewDetails", "true");
ModelAndView modelAndView = myController.handleRequest(request, response);
assertEquals("Incorrect view name", detailsViewName, modelAndView.getViewName());
}
Spring JDBC
 Issues with direct use of JDBC
 SQL Exceptions
 JdbcTemplate
JdbcTemplate jt = new JdbcTemplate(datasource);
jt.execute(“delete from mytable”);
jt.execute(“select * from department”);
 Stateless and Threadsafe class
Spring ORM
 What is ORM?
 DAO Support
 Transaction Management
 Object Query Language
 When to choose ORM?
Overview of Hibernate
 What is Hibernate?
 SessionFactory
 Session
 Transaction
 Hibernate Properties
 Mapping Files
 Eager/Lazy
 Dialect
Spring’s support for Hibernate
 Easy configuration of Hibernate Properties
 IOC feature
 HibernateTemplate
 HibernateDaoSupport
Session Factory setup in Spring Container
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-
method="close">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>product.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
</value>
</property>
</bean>
</beans>
Session Factory setup in Spring Container
<beans>
<bean id="myProductDao" class="product.ProductDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
public class ProductDaoImpl implements ProductDao {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public Collection loadProductsByCategory(String category) throws DataAccessException {
return this.hibernateTemplate.find("from test.Product product where product.category=?",
category);
}
}
Session Factory setup in Spring Container -
HibernateDaoSupport
public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao {
public Collection loadProductsByCategory(String category) throws DataAccessException {
return getHibernateTemplate().find("from test.Product product where product.category=?",
category);
}
}
Benefits of Spring with ORM
 Ease of testing
 Common data access exceptions
 General resource management
 Integrated transaction management
 Programmatic and Declarative transaction support
(TransactionTemplate)
22
Scheduling with Spring
 Where to use Scheduling?
 Generate periodic reports
 Invoke a batch process
 Execute periodic application maintenance tasks
 Spring Provides support for Scheduling
 Timers – Java’s Built in Scheduler
 Quartz – Open Source solution by OpenSymphony
23
Spring Scheduler
public class ExampleBusinessObject {
// properties and collaborators
public void doIt() {
// do the actual work
}
}
<bean id="exampleBusinessObject" class="examples.ExampleBusinessObject"/>
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="exampleBusinessObject" />
<property name="targetMethod" value="doIt" />
<property name="concurrent" value="false" />
</bean>
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref=" jobDetail" />
<!-- run every morning at 6 AM -->
<property name="cronExpression" value="0 0 6 * * ?" />
</bean>
Spring MVC
public interface Controller {
/**
* Process the request and return a ModelAndView object which the DispatcherServlet will render.
*/
ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
Spring JMS
 Asynchronous Messaging
 Provides support for sending/consuming JMS Messages
 JMSTemplate
public class JmsQueueSender {
private JmsTemplate jmsTemplate;
private Queue queue;
public void setConnectionFactory(ConnectionFactory cf) {
this.jmsTemplate = new JmsTemplate102(cf, false);
}
public void setQueue(Queue queue) {
this.queue = queue;
}
public void simpleSend() {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("hello queue world");
}
});
}
}
Spring E-Mail
 Spring Framework provides a helpful utility library for
sending email that shields the user from the specifics of
the underlying mailing system
public class SimpleOrderManager {
private MailSender mailSender;
private SimpleMailMessage templateMessage;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
public void placeOrder(Order order) {
// Do the business calculations...
// Call the collaborators to persist the order...
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
msg.setTo(order.getCustomer().getEmailAddress());
msg.setText(“Thank you for placing order. Your order number is “ + order.getOrderNumber());
try{
this.mailSender.send(msg);
}
catch(MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
}
}
Spring E-Mail
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="customerservice@mycompany.com"/>
<property name="subject" value="Your order"/>
</bean>
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
Spring Batch
 Lightweight, comprehensive batch framework
 Item Provider, Item Processor
 Is part of Spring Framework
Spring MVC
 Uses MVC Framework
 Designed around a DispatcherServlet that dispatches requests to
handlers, with configurable handler mappings, view resolution
 Spring Web MVC allows you to use any object as a command or
form object
 ModelAndView instance consists of a view name and a model Map
 JSP form tag library
 Simple yet powerful JSP tag library known as the Spring tag library
 Support for other MVC frameworks
Spring MVC
Quick Recap
 Open Source and Light weight application framework
 Bean Factory and Beans
 IOC or Dependency Injection
 Spring AOP
 Program to Interfaces
 Also, Spring comes with .Net flavour (Spring.net)
References
 Professional Java Development with Spring Framework
– Rod Johnson
 http://static.springsource.org
 http://www.springbyexample.org
Spring framework  part 2

Spring framework part 2

  • 1.
  • 2.
    2 Contents  Recap ofearlier session’s points  Spring AOP  Spring Mock Testing  Spring ORM (With Hibernate)  Spring Scheduler  Spring JMS  Spring Email  Spring Batch  Spring MVC  Spring in Real World  Quick Recap  References  Questions?
  • 3.
    3 Recap of EarlierSession’s Points  What is Spring framework?  IOC and Dependency Injection  Different types of Injection  Bean Factory and Beans  Wiring  Bean Post Processor  Plumbing of Code  Program to Interfaces
  • 4.
    4 Spring AOP  AOPcomplements OOP  The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect  crosscutting concerns Audit Authentication Logging Transaction Support
  • 5.
    5 Spring AOP concepts Aspect  Advice  Join Point  Point cut  Target Object  AOP Proxy  Weaving
  • 6.
    6 Types of Advices Before Advice - (Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point unless it throws an exception)  After returning advice – (Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception)  After throwing advice – (Advice to be executed if a method exits by throwing an exception)  After advice – (Advice to be executed regardless of the means by which a join point exits normal or exceptional return)
  • 7.
    7 Point cuts  Allsetter methods  All methods returning void  All methods in a package  All methods with only one parameter  With Regular Expression  Programmable point cut model
  • 8.
    8 AOP Proxy  SpringAOP defaults to using standard J2SE dynamic proxies for AOP proxies  This enables any interface (or set of interfaces) to be proxied.  AspectJ Support  How to enable AspectJ Support <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
  • 9.
    9 Various PointCut Definitions •execution - for matching method execution join points, this is the primary pointcut designator used when working with Spring AOP • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types
  • 10.
    10 Pointcut Example •@Aspect •public classSystemArchitecture { • /** • * A join point is in the web layer if the method is defined in a type in the com.xyz.someapp.web package or any sub-package under that. • */ • @Pointcut("within(com.xyz.someapp.web..*)") • public void inWebLayer() {} • /** • * A join point is in the service layer if the method is defined in a type in the com.xyz.someapp.service package or any sub-package under that. • */ • @Pointcut("within(com.xyz.someapp.service..*)") • public void inServiceLayer() {} • /** • * A join point is in the data access layer if the method is defined in a type in the com.xyz.someapp.dao package or any sub-package under that. • */ • @Pointcut("within(com.xyz.someapp.dao..*)") • public void inDataAccessLayer() {} • /** • * A business service is the execution of any method defined on a service interface. * • */ • @Pointcut("execution(* com.xyz.someapp.service.*.*(..))") • public void businessService() {} • • /** • * A data access operation is the execution of any method defined on a dao interface. This definition assumes that interfaces are placed in the • * "dao" package, and that implementation types are in sub-packages. • */ • @Pointcut("execution(* com.xyz.someapp.dao.*.*(..))") • public void dataAccessOperation() {} •}
  • 11.
  • 12.
    12 Spring Mock Testing What is a Mock object?  Different providers of Mock objects  Mock Objects  EasyMock  JMock  Web - org.springframework.mock.web  MockHttpServletRequest  MockHttpServletResponse  MockHttpSession  JNDI - org.springframework.mock.jndi  General Utilities - org.springframework.test.util
  • 13.
    13 Spring Mock Testing publicvoid final testDetails throws Exception { MyController myController = new MyController(); myController.setDetailsView("detailsName"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setMethod("POST"); request.addParameter("viewDetails", "true"); ModelAndView modelAndView = myController.handleRequest(request, response); assertEquals("Incorrect view name", detailsViewName, modelAndView.getViewName()); }
  • 14.
    Spring JDBC  Issueswith direct use of JDBC  SQL Exceptions  JdbcTemplate JdbcTemplate jt = new JdbcTemplate(datasource); jt.execute(“delete from mytable”); jt.execute(“select * from department”);  Stateless and Threadsafe class
  • 15.
    Spring ORM  Whatis ORM?  DAO Support  Transaction Management  Object Query Language  When to choose ORM?
  • 16.
    Overview of Hibernate What is Hibernate?  SessionFactory  Session  Transaction  Hibernate Properties  Mapping Files  Eager/Lazy  Dialect
  • 17.
    Spring’s support forHibernate  Easy configuration of Hibernate Properties  IOC feature  HibernateTemplate  HibernateDaoSupport
  • 18.
    Session Factory setupin Spring Container <beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy- method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> </property> </bean> </beans>
  • 19.
    Session Factory setupin Spring Container <beans> <bean id="myProductDao" class="product.ProductDaoImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> </beans> public class ProductDaoImpl implements ProductDao { private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } public Collection loadProductsByCategory(String category) throws DataAccessException { return this.hibernateTemplate.find("from test.Product product where product.category=?", category); } }
  • 20.
    Session Factory setupin Spring Container - HibernateDaoSupport public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao { public Collection loadProductsByCategory(String category) throws DataAccessException { return getHibernateTemplate().find("from test.Product product where product.category=?", category); } }
  • 21.
    Benefits of Springwith ORM  Ease of testing  Common data access exceptions  General resource management  Integrated transaction management  Programmatic and Declarative transaction support (TransactionTemplate)
  • 22.
    22 Scheduling with Spring Where to use Scheduling?  Generate periodic reports  Invoke a batch process  Execute periodic application maintenance tasks  Spring Provides support for Scheduling  Timers – Java’s Built in Scheduler  Quartz – Open Source solution by OpenSymphony
  • 23.
    23 Spring Scheduler public classExampleBusinessObject { // properties and collaborators public void doIt() { // do the actual work } } <bean id="exampleBusinessObject" class="examples.ExampleBusinessObject"/> <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> <property name="concurrent" value="false" /> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref=" jobDetail" /> <!-- run every morning at 6 AM --> <property name="cronExpression" value="0 0 6 * * ?" /> </bean>
  • 24.
    Spring MVC public interfaceController { /** * Process the request and return a ModelAndView object which the DispatcherServlet will render. */ ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) throws Exception; }
  • 25.
    Spring JMS  AsynchronousMessaging  Provides support for sending/consuming JMS Messages  JMSTemplate public class JmsQueueSender { private JmsTemplate jmsTemplate; private Queue queue; public void setConnectionFactory(ConnectionFactory cf) { this.jmsTemplate = new JmsTemplate102(cf, false); } public void setQueue(Queue queue) { this.queue = queue; } public void simpleSend() { this.jmsTemplate.send(this.queue, new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage("hello queue world"); } }); } }
  • 26.
    Spring E-Mail  SpringFramework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system public class SimpleOrderManager { private MailSender mailSender; private SimpleMailMessage templateMessage; public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void setTemplateMessage(SimpleMailMessage templateMessage) { this.templateMessage = templateMessage; } public void placeOrder(Order order) { // Do the business calculations... // Call the collaborators to persist the order... SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage); msg.setTo(order.getCustomer().getEmailAddress()); msg.setText(“Thank you for placing order. Your order number is “ + order.getOrderNumber()); try{ this.mailSender.send(msg); } catch(MailException ex) { // simply log it and go on... System.err.println(ex.getMessage()); } } }
  • 27.
    Spring E-Mail <bean id="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="mail.mycompany.com"/> </bean> <!-- this is a template message that we can pre-load with default state --> <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from" value="customerservice@mycompany.com"/> <property name="subject" value="Your order"/> </bean> <bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager"> <property name="mailSender" ref="mailSender"/> <property name="templateMessage" ref="templateMessage"/> </bean>
  • 28.
    Spring Batch  Lightweight,comprehensive batch framework  Item Provider, Item Processor  Is part of Spring Framework
  • 29.
    Spring MVC  UsesMVC Framework  Designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution  Spring Web MVC allows you to use any object as a command or form object  ModelAndView instance consists of a view name and a model Map  JSP form tag library  Simple yet powerful JSP tag library known as the Spring tag library  Support for other MVC frameworks
  • 30.
  • 31.
    Quick Recap  OpenSource and Light weight application framework  Bean Factory and Beans  IOC or Dependency Injection  Spring AOP  Program to Interfaces  Also, Spring comes with .Net flavour (Spring.net)
  • 32.
    References  Professional JavaDevelopment with Spring Framework – Rod Johnson  http://static.springsource.org  http://www.springbyexample.org