From:
jkmgroup
Views: 153
Comments: 0
Amrapali Spring Meadows|8860623210|Amrapali Spring Meadows Noida Extension|
Amrapali Spring Meadows is latest new project of Amrapali Group. Amrapali Spring Meadows residential project is located at Noida Extension.
From:
greymatterseo
Views: 52
Comments: 0
In this article, we thought of explaining you the actual concepts of Cloud; explaining you what Scala and PaaS are, and their association with Spring Java web programming and News taking rounds of Java’s integration with Cloud computing.
From:
SoftwebSolutions
Views: 560
Comments: 0
JFX (java FX) web application development company Chicago delivers rich internet applications created by professional java programmers with javafx platform and spring framework.
Slide 1: Spring Framework & Friends
Nadav Soferman, June 2007
Slide 2: References
• The following resources were used for building this presentation:
– Spring Framework 2.0 Reference Manual – Wikipedia articles about AOP and IoC – Spring Framework presentation by Adam Waldal – Introduction to the Spring Framework by Mark Eagle
– “Inversion of Control Containers and the Dependency Inject
– J2EE: Introduction, Practice and Software Architecture by D Loeffler
Slide 3: Outline
• Spring overview
– – – What is Spring? Java, JEE (J2EE), Spring and history Spring as a framework
• • •
IoC – Inversion of Control AOP – Aspect Oriented Programming Some Spring features
– – – – – – JDBC Hibernate Transaction Management Remote access Scheduling Testing
• •
Training description Summary
Slide 4: Spring Overview
Slide 5: What is Spring?
• The Spring Framework is an open source web application framework for the Java platform • Spring is actually a collection of many different components • Reduces code and speeds up development • Enables applications to be coded from POJOs (Plain Old Java Object) • Alternative and replacement for the Enterprise JavaBean model
Slide 6: What is Spring?
• Spring is a non-invasive and portable framework that allows you to introduce as much or as little as you want to your application • Promotes decoupling and reusability • Allows developers to focus more on reused business logic and less on plumbing problems • Based on various existing open source frameworks and packages • Integrates with popular packages (Hibernate, TopLink, AspectJ, Struts, EJB, etc.)
Slide 7: Spring Mission Statement
• We believe that:
– J2EE should be easier to use – It's best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero. – JavaBeans offer a great way of configuring applications. – OO design is more important than any implementation technology, such as J2EE. – Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from. – Testability is essential, and a framework such as Spring should help make your code easier to test.
• We aim that:
– Spring should be a pleasure to use – Your application code should not depend on Spring APIs – Spring should not compete with good existing solutions, but should foster integration. (For example, JDO, Toplink, and Hibernate are great O/R mapping solutions. We don't need to develop another one.)
Slide 8: Java, JEE (J2EE), Spring and history
Java
Everybody needs the same
(Jakarta Commons, OR/M tools, XML, etc.)
Utility Libraries
Everybody really needs the same
(Online server, worker threads, transactions, DB access, Web applications, cluster support, etc.)
Sun J2EE Standard
J2EE is too complex and heavy. Code is too technical and not OO enough
Spring Framework
Sun wakes up (easier & lighter) Making it stronger and integrating with JEE
JEE - EJB3
New Framework versions
Slide 9: What is J2EE?
• Java2 Enterprise Edition • A collection of Java technologies to build distributed applications (incl. web applications) • A set of specifications to write applications against (that will run in an application server) • A set of specifications to define the behavior of application servers and hence to write application servers against • Very complex if considering it's entire breadth and depth • Not a software product (IDE, server, whatever) • Targeted at the same application space as Microsoft's .Net, which uses some of the same architectural concepts
Slide 10: What is J2EE? • J2SE APIs:
– JDBC (Java Database Connectivity) – Java IDL ((Corba) Interface Definition Language) – RMI-IIOP ((Java) Remote Method Invocation over (Corba) Internet Inter-Orb Protocol) – JNDI (Java Naming and Directory Interface) – JAXP (Java API for XML Processing) – JAAS (Java Authentication and Authorization Service)
Slide 11: What is J2EE?
• • • • • • • • • • • • • • • • EJB (Enterprise JavaBeans) Servlet JSP (Java Server Pages) JMS (Java Messaging Service) JTA (Java Transaction API) JavaMail JAF Connector (J2EE Connector Architecture) Web Services JAX-RPC (Java API for XML Remote Procedure Calls) SAAJ (SOAP with Attachments API forJava) JAXR (Java API for XML Registries) J2EE Management JMX (Java Management Extensions) J2EE Deployment JACC (Java Authorization Service Provider Contract for Containers)
Slide 12: J2EE component overview
• Servlet
– Java class that consumes HTTP request and produces HTTP response – Front controller in web apps, Gateway to HTTP-based protocols (SOAP)
• JSP
– "markup (HTML) file with Java code", compiled to Servlet – View in web apps
• EJB
– Application ("business") logic and/or data
• Resource adapter ("connector")
– Link between app server and enterprise information system (EIS) (SAP, Siebel, Message Oriented Middleware (MOM), Host, ...)
• Applet, application
Slide 13: J2EE Application Server
• Runtime environment for J2EE components • (Logically) made up of containers:
– Web container (hosts Servlets/JSPs) – EJB container (hosts EJBs)
• Provides services to (and encapsulates) components:
– Thread pooling – State management – Security
• Authentication, authorization, access control, encryption
– Transactions
• Is a web server, Corba server, includes a transaction manager, ...
Slide 14: J2EE Architectures
• Simple Web-centric application:
Slide 15: J2EE Architectures • Web application using EJBs:
Slide 16: Protocols
Slide 17: Spring as a framework • And now…
Slide 18: Spring as a framework
Slide 19: IoC Inversion of Control
Slide 20: IoC Overview • Inversion of Control (IoC), is an objectoriented programming principle that can be used to reduce coupling inherent in computer programs • “Don’t talk to strangers” • “Don’t call me I will call you” • IoC is also known as the Dependency Injection • Easy to maintain and reuse • Testing is easier
Slide 21: IoC Overview
Non-IoC IoC
Slide 22: IoC Overview
Non-IoC Example:
class MovieLister... private MovieFinder finder; public MovieLister() { finder = new ColonMovieFinder(“m1.txt”); }
class ColonMovieFinder... private String fileName; public ColonMovieFinder(String fileName) { this.fileName = fileName; } public List findAll() { ... }
public interface MovieFinder { List findAll(); }
Slide 23: IoC Overview
Constructor Injection IoC:
class MovieLister... public MovieLister(MovieFinder finder) { this.finder = finder; }
Slide 24: IoC Overview
Setter Injection IoC:
class MovieLister... private MovieFinder finder; public void setFinder(MovieFinder finder) { this.finder = finder; }
class ColonMovieFinder... private String fileName; public void setFileName(String fileName) { this.fileName = fileName; }
Slide 25: IoC Overview
• Many IoC implementations:
– Java:
• • • • • • • • • • • HiveMind PicoContainer Spring Framework Apache Excalibur Seasar Spring.NET ObjectBuilder Structuremap Castle Project Seasar Titan
– .NET
Slide 26: IoC in Spring
Spring’s bean definition XML file:
<beans> <bean id="MovieLister“ class=“example.MovieLister"> <property name="finder"> <ref local="MovieFinder"/> </property> </bean> <bean id="MovieFinder“ class=“example.ColonMovieFinder"> <property name="fileName"> <value>movies1.txt</value> </property> </bean> </beans>
Slide 27: IoC in Spring
Spring’s Bean Factory creation and usage: public void testWithSpring() throws Exception { BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“spring.xml”)); MovieLister lister = (MovieLister)factory.getBean("MovieLister"); Movie[] movies = lister.moviesDirectedBy("Sergio Leone"); assertEquals("Once Upon a Time", movies[0].getTitle()); }
Slide 28: IoC in Spring – Setter Injection
Definition of beans:
<bean id="exampleBean" class="examples.ExampleBean"> <!-- setter injection using the nested <ref/> element --> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <!-- setter injection using the neater 'ref' attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Java object with setters:
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } }
Slide 29: IoC in Spring – Constructor Injection
Definition of beans:
<bean id="exampleBean" class="examples.ExampleBean"> <!-- constructor injection using the nested <ref/> element --> <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref="yetAnotherBean"/> <constructor-arg type="int" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
Java object with a constructor:
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean( AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; } }
Slide 30: IoC in Spring – Bean Reference
<bean id=“myService” class=“examples.MyService”>
Reference to any bean in the same container:
<property name=“dao”> <ref bean=“myDAO”/> </property> </bead> <bean id=“myService” class=“examples.MyService”>
Reference to a bean in the same XML file:
<property name=“dao”> <ref local=“myLocalDAO”/> </property> </bead> <bean id=“myService” class=“examples.MyService”> <property name=“dao”>
Inner bean:
<bean class=“examples.MyDAO"> <property name="name" value=“apple"/> <property name=“kind" value=“big"/> </bean> </property> </bead>
Slide 31: IoC in Spring – Bean Scopes • ‘Singleton’ bean scope:
Slide 32: IoC in Spring – Bean Scopes • ‘prototype’ bean scope:
Slide 33: IoC in Spring – Auto Wire by Type
Definition of beans with auto wire by type:
<bean id=“oneDataSource” class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> ... </bean> <bead id=“oneFriend” class=“examples.MyFriendImpl”> <property name=“name" value=“apple"/> </bean> <bead id=“myService” class=“examples.MyService” autowire=“byType”> </bean>
Java object with setters:
public class MyService { private DataSource dataSource; private MyFriend myFriend; public void setDataSource(dataSource) { this.dataSource = dataSource; } public void setMyFriend(myFriend) { this.myFriend = myFriend; } ... }
Slide 34: IoC in Spring – Auto Wire by Name
Definition of beans with auto wire by name:
<bean id=“dataSource” class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> ... </bean> <bead id=“myFriend” class=“examples.MyFriendImpl”> <property name=“name" value=“apple"/> </bean> <bead id=“myService” class=“examples.MyService” autowire=“byName”> </bean>
Java object with setters:
public class MyService { private DataSource dataSource; private MyFriend myFriend; public void setDataSource(dataSource) { this.dataSource = dataSource; } public void setMyFriend(myFriend) { this.myFriend = myFriend; } ... }
Slide 35: IoC in Spring – Lazily-instantiated beans
A single lazy-init bean definition:
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/> <bean name="not.lazy" class="com.foo.AnotherBean"/>
Defining all beans as lazy-init:
<beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans>
Slide 36: IoC in Spring – Bean definition inheritance
Definition of a bean that inherit from an abstract bean definition:
<bean id="inheritedTestBeanWithoutClass" abstract="true"> <property name="name" value="parent"/> <property name="age" value="1"/> </bean> <bean id="inheritsWithClass“ class="org.springframework.beans.DerivedTestBean“ parent="inheritedTestBeanWithoutClass" init-method="initialize"> <property name="name" value="override"/> <!-- age will inherit the value of 1 from the parent bean definition--> </bean>
Slide 37: IoC in Spring – Customizing configuration metadata
Definitions of beans with properties-based configuration:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:com/foo/jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
Programmatic configuration of bean definition files:
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml")); // bring in some property values from a Properties file PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.setLocation(new FileSystemResource("jdbc.properties")); // now actually do the replacement cfg.postProcessBeanFactory(factory);
Slide 38: AOP Aspect Oriented Programming
Slide 39: AOP Overview
• Aspect-oriented programming (AOP) complements OOP by providing another way of thinking about program structure • In addition to classes, AOP gives you aspects:
– Aspects enable modularization of concerns such as transaction management and logging that cut across multiple types and objects. (Such concerns are often termed crosscutting concerns.)
• Aspects can be added or removed as needed without changing your code
Slide 40: AOP Overview
• Many AOP implementations:
– Java:
• The Spring Framework • AspectJ • JBoss AOP • Jakarta Hivemind • Many more…
– .NET:
• The Spring.NET Framework • Aspect.NET • ACA.NET
– Many more for all other languages
Slide 41: AOP Overview
Basic money transfer method:
void transfer(Account fromAccount, Account toAccount, int amount) { if (fromAccount.getBalance() < amount) { throw new InsufficientFundsException(); } fromAccount.withdraw(amount); toAccount.deposit(amount); }
Slide 42: AOP Overview
Money transfer method with cross cutting concerns:
void transfer(Account fromAccount, Account toAccount, int amount) { if (!getCurrentUser().canPerform(OP_TRANSFER)) { throw new SecurityException(); } if (amount < 0) { throw new NegativeTransferException(); } if (fromAccount.getBalance() < amount) { throw new InsufficientFundsException(); } Transaction tx = database.newTransaction(); try { fromAccount.withdraw(amount); toAccount.deposit(amount); tx.commit(); systemLog.logOperation(OP_TRANSFER, fromAccount, toAccount, amount); } catch(Exception e) { tx.rollback(); } }
Slide 43: AOP Overview
• • • • • • • • Aspect
– – – – – – – – A modularization of a concern that cuts across multiple objects. e.g. transaction management A point during the execution of a program, such as the execution of a method Action taken by an aspect at a particular join point ("around,“ "before" and "after“). A predicate that matches join points. Declaring additional methods or fields on behalf of a type Object being advised by one or more aspects. An object created by the AOP framework in order to implement the aspect contracts Linking aspects with other application types or objects to create an advised object.
Join point Advice Pointcut Introduction Target object AOP proxy Weaving
Slide 44: AOP in Spring
• • • • • • • • Aspect
– – – – – Aspects are implemented using regular classes A join point always represents a method execution. Model an advice as an interceptor, maintaining a chain of interceptors "around" the join point Spring uses the AspectJ pointcut language by default Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any proxied object Spring AOP is implemented using runtime proxies, this object will always be a proxied object A JDK dynamic proxy or a CGLIB proxy Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime
Join point Advice Pointcut Introduction Target object
– – –
AOP proxy Weaving
Slide 45: AOP in Spring • Spring AOP has built in aspects such as providing transaction management and performance monitoring • Two options:
– Spring AOP – AspectJ
• IoC + AOP is a great combination that is non-invasive
Slide 46: AOP in Spring
Slide 47: AOP in Spring
Aspect for logging:
package com.myorg.springaop.examples; import org.aspectj.lang.ProceedingJoinPoint; public class MyLoggingAspect { public Object log(ProceedingJoinPoint call) throws Throwable { System.out.println("from logging aspect: entering method [" + call.toShortString() +"] with param:"+call.getArgs()[0] ); Object point = call.proceed(); System.out.println("from logging aspect: exiting method [" + call.toShortString() + "with return as:" +point); return point; } }
Slide 48: AOP in Spring
Bean definition for logging :
<bean id=“loggingAspect" class="com.myorg.springaop.examples.MyLoggingAspect"/> <aop:config> <aop:aspect ref=“loggingAspect"> <aop:pointcut id="myCutLogging" expression="execution(* com.myorg.springaop.examples.MyService*.*(..))"/> <aop:around pointcut-ref="myCutLogging" method="log"/> </aop:aspect> </aop:config>
Slide 49: AOP in Spring
Aspect for security check:
package com.myorg.springaop.examples; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.userdetails.UserDetails; import org.aspectj.lang.ProceedingJoinPoint; public class MySecurityAspect { public Object checkSecurity(ProceedingJoinPoint call) throws Throwable { System.out.println("from security aspect: checking method call for " + call.toShortString()); Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = ""; if (obj instanceof UserDetails) { username = ((UserDetails)obj).getUsername(); } else { username = obj.toString(); } //Do authorization check here System.out.println("from security aspect: authenticated user is "+username); return call.proceed(); } }
Slide 50: AOP in Spring
Bean definition for security check :
<bean id=“securityAspect" class="com.myorg.springaop.examples.MySecurityAspect"/> <aop:config> <aop:aspect ref=“securityAspect"> <aop:pointcut id="myCutSecurity" expression="execution(* com.myorg.springaop.examples.MyService*.*(..))"/> <aop:around pointcut-ref="myCutSecurity" method="checkSecurity"/> </aop:aspect> </aop:config>
Slide 51: AOP in Spring
Bean definition for transactionality:
<bean id="txManager“ class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="myDataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="myCutTx" expression="execution(* com.myorg.springaop.examples.MyService*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="myCutTx"/> </aop:config>
Slide 52: Spring JDBC Support
Slide 53: Spring JDBC support
• Utilities for JDBC SQL access (JdbcTemplate) • Based on Spring IoC concepts
– Define data source, connection and transaction settings in spring XML definition files
• Hides various technical aspects:
– Database connection management – Database transaction management – No specific database or data source binding – No need to catch exceptions (all exceptions are runtime). – Better hierarchy of exceptions (instead of a single SQLException).
Slide 54: Spring JDBC support
A simple query for getting the number of rows in a relation:
int rowCount = this.jdbcTemplate.queryForInt("select count(0) from t_accrual");
A simple query using a bind variable:
int countOfActorsNamedJoe = this.jdbcTemplate.queryForInt( "select count(0) from t_actors where first_name = ?", new Object[]{"Joe"});
Querying for a String:
String surname = (String) this.jdbcTemplate.queryForObject( "select surname from t_actor where id = ?", new Object[]{new Long(1212)}, String.class);
Slide 55: Spring JDBC support
Querying and populating a number of domain objects.:
Collection actors = this.jdbcTemplate.query( "select first_name, surname from t_actor", new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setSurname(rs.getString("surname")); return actor; } } );
Updating (INSERT/UPDATE/DELETE):
this.jdbcTemplate.update( "insert into t_actor (first_name, surname) values (?, ?)", new Object[] {"Leonor", "Watling"}); this.jdbcTemplate.update("update t_actor set weapon = ? where id = ?", new Object[] {"Banjo", new Long(5276)}); this.jdbcTemplate.update("delete from orders");
Slide 56: Spring JDBC support
Java DAO class that uses JdbcTemplate:
public class JdbcCorporateEventDao implements CorporateEventDao { private JdbcTemplate jdbcTemplate; public int countEmployees(String name) { return this.jdbcTemplate.queryForInt("select count(*) from employee where name = ?“ new Object[]{name}); } }
Definitions of data source, jdbcTemplate and DAO beans:
<beans ... > <bean id="corporateEventDao" class="com.example.JdbcCorporateEventDao"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <bean id=“jdbcTemplate” class=“org.springframework.jdbc.core.JdbcTemplate”> <property name="dataSource" ref="dataSource"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>
Slide 57: Spring Hibernate Support & Transaction Management
Slide 58: Spring Hibernate Support • Utilities for Hibernate usage (HibernateTemplate) • Includes transaction management support (Hibernate or JTA transactions) • Based on Spring IoC concepts
– Define data source, session factory and transaction settings in spring XML definition files
Slide 59: Spring Hibernate Support
Definitions of data source, session factory and DAO beans:
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <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="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/myds"/> </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> <bean id="myProductDao" class="product.ProductDaoImpl"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> </beans>
Slide 60: Spring Hibernate Support
Java DAO classes that uses HibernateTemplate:
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); } } public class ProductDaoImpl implements ProductDao {
private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); }
public Collection loadProductsByCategory(final String category) throws DataAccessException { return this.hibernateTemplate.execute(new HibernateCallback() { public Object doInHibernate(Session session) { Criteria criteria = session.createCriteria(Product.class); criteria.add(Expression.eq("category", category)); criteria.setMaxResults(6); return criteria.list(); } }; } }
Slide 61: Spring Hibernate Support
Java DAO classes that extend HibernateDaoSupport:
public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao { public Collection loadProductsByCategory(String category) throws DataAccessException { return this.getHibernateTemplate().find( "from test.Product product where product.category=?", category); } }
public class HibernateProductDao extends HibernateDaoSupport implements ProductDao { public Collection loadProductsByCategory(String category) throws DataAccessException, MyException { Session session = getSession(false); try { Query query = session.createQuery( "from test.Product product where product.category=?"); query.setString(0, category); List result = query.list(); if (result == null) { throw new MyException("No search results."); } return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } } }
Slide 62: Spring Hibernate Support
Java DAO classes that uses SessionFactory directly:
public class ProductDaoImpl implements ProductDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Collection loadProductsByCategory(String category) { return this.sessionFactory.getCurrentSession() .createQuery("from test.Product product where product.category=?") .setParameter(0, category) .list(); } }
Slide 63: Programmatic transaction demarcation
Definition of beans using Hibernate transaction manager:
<beans> <bean id="myTxManager“ class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> <bean id="myProductService" class="product.ProductServiceImpl"> <property name="transactionManager" ref="myTxManager"/> <property name="productDao" ref="myProductDao"/> </bean> </beans>
Java class that uses the transaction manager for creating transactions:
public class ProductServiceImpl implements ProductService { private TransactionTemplate transactionTemplate; private ProductDao productDao; public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionTemplate = new TransactionTemplate(transactionManager); } public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void increasePriceOfAllProductsInCategory(final String category) { this.transactionTemplate.execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { List productsToChange = this.productDao.loadProductsByCategory(category); // do the price increase... } }); }
Slide 64: Declarative transaction demarcation
Definition of a service bean with AOP transaction management:
<beans> <bean id="myTxManager“ class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> <bean id="myProductService“ class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="myTxManager"/> <property name="target" ref="myProductServiceTarget"/> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>
Java class of the service without any transaction-related code:
public class ProductServiceImpl implements ProductService { private ProductDao productDao; public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void increasePriceOfAllProductsInCategory(final String category) { List productsToChange = this.productDao.loadProductsByCategory(category); // ... } }
Slide 65: Declarative transaction demarcation
Schema-based definitions of beans with transaction management:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- SessionFactory, DataSource, etc. omitted -->
<bean id="myTxManager“ class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"/> </bean> <aop:config> <aop:pointcut id="productServiceMethods" expression="execution(* product.ProductService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/> </aop:config> <tx:advice id="txAdvice" transaction-manager="myTxManager"> <tx:attributes> <tx:method name="increasePrice*" propagation="REQUIRED"/> <tx:method name="someOtherBusinessMethod" propagation="REQUIRES_NEW"/> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <bean id="myProductService" class="product.SimpleProductService"> <property name="productDao" ref="myProductDao"/> </bean> </beans>
Slide 66: Spring Remote Access Support
Slide 67: Remote Access
• Easily export services using various remoting protocols:
– – – – – RMI HTTP Invokers Web Services JMS More…
• Easily access remote services from the clientside • Completely hide the actual protocol • Easily switch between various protocols, implementations and mocks
Slide 68: Remote Access
Account service - interface and implementation:
public class Account implements Serializable { private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } } public interface AccountService { public void insertAccount(Account account); public List getAccounts(String name); } public interface RemoteAccountService extends Remote { public void insertAccount(Account account) throws RemoteException; public List getAccounts(String name) throws RemoteException; } public class AccountServiceImpl implements AccountService { public void insertAccount(Account acc) { // do something... } public List getAccounts(String name) { // do something... } }
Slide 69: Remote Access
Definition of the account service implementation bean:
<bean id="accountService" class="example.AccountServiceImpl"> <!-- any additional properties, maybe a DAO? --> </bean>
Exposing the account service for RMI access:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter"> <property name="serviceName" value="AccountService"/> <property name="service" ref="accountService"/> <property name="serviceInterface" value="example.AccountService"/> <!-- defaults to 1099 --> <property name="registryPort" value="1199"/> </bean>
Slide 70: Remote Access
Client-side Java code usage of the account service:
public class SimpleObject { private AccountService accountService; public void setAccountService(AccountService accountService) { this.accountService = accountService; } public void work() { Account account = new Account(); account.setName(“my_name”); this.accountService.insertAccount(account); } }
Definition of client-side access to the remote RMI account service:
<bean class="example.SimpleObject"> <property name="accountService" ref="accountService"/> </bean> <bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean"> <property name="serviceUrl" value="rmi://HOST:1199/AccountService"/> <property name="serviceInterface" value="example.AccountService"/> </bean>
Definition of an alternative mock implementation of the account service:
<bean id="accountService" class=“example.AccountServiceMock”> </bean>
Slide 71: Remote Access
Exposing the account service for remote HTTP invoker:
<bean name="/AccountService“ class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter"> <property name="service" ref="accountService"/> <property name="serviceInterface" value="example.AccountService"/> </bean>
Definition of client-side bean for accessing a remote HTTP invoker service:
<bean id="httpInvokerProxy“ class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"> <property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/> <property name="serviceInterface" value="example.AccountService"/> </bean>
Slide 72: Spring Scheduling Support
Slide 73: Scheduling • Easily run methods of POJOs as periodic jobs • Easily define jobs execution in intervals or according to cron expressions • Prevent concurrent execution of jobs
Slide 74: Scheduling
A POJO with a method that should be executed periodically:
public class ExampleBusinessObject { // properties and collaborators public void doIt() { // do the actual work } }
Definition of the doIt method as a Quartz Job Detail:
<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>
Slide 75: Scheduling
Definition of Quartz triggers and scheduler:
<bean id="simpleTrigger“ class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="jobDetail" /> <property name="startDelay" value="10000" /> <property name="repeatInterval" value="50000" /> </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> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronTrigger" /> <ref bean="simpleTrigger" /> </list> </property> </bean>
Slide 76: Spring Testing Infrastructure
Slide 77: Testing Infrastructure • JUnit integration (JUnit base classes) • Automatic (auto-wire) injection of beans requires by tests • Easy transaction management and database access • Utility methods for easier testing
Slide 78: Testing Infrastructure
JUnit test with dependency injections:
public final class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests { // this instance will be (automatically) dependency injected private HibernateTitleDao titleDao; // a setter method to enable DI of the 'titleDao' instance variable public void setTitleDao(HibernateTitleDao titleDao) { this.titleDao = titleDao; } public void testLoadTitle() throws Exception { Title title = this.titleDao.loadTitle(new Long(10)); assertNotNull(title); } // specifies the Spring configuration to load for this test fixture protected String[] getConfigLocations() { return new String[] { "classpath:com/foo/daos.xml" }; } }
Slide 79: Testing Infrastructure
Definitions of beans used by the JUnit tests:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans> <!-- this bean will be injected into the HibernateTitleDaoTests class --> <bean id="titleDao" class="com.foo.dao.hibernate.HibernateTitleDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionFactory“ class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- dependencies elided for clarity --> </bean> </beans>
Slide 80: Testing Infrastructure
JUnit test with transactional data source access::
public abstract class AbstractClinicTests extends AbstractTransactionalDataSourceSpringContextTests { protected Clinic clinic; public void setClinic(Clinic clinic) { this.clinic = clinic; } public void testGetVets() { Collection vets = this.clinic.getVets(); assertEquals('JDBC query must show the same number of vets', jdbcTemplate.queryForInt('SELECT COUNT(0) FROM VETS'), vets.size()); Vet v1 = (Vet) EntityUtils.getById(vets, Vet.class, 2); assertEquals('Leary', v1.getLastName()); assertEquals(1, v1.getNrOfSpecialties()); assertEquals('radiology', ((Specialty) v1.getSpecialties().get(0)).getName()); } protected String[] getConfigLocations() { return new String[] { "classpath:com/foo/test.xml" }; } }
Slide 81: Testing Infrastructure
Abstract classes with differerent spring XML files:
public final class HibernateClinicTests extends AbstractClinicTests { protected String[] getConfigLocations() { return new String[] { "/org/sf/samples/petclinic/hibernate/applicationContext-hibernate.xml" }; } }
public final class MocksClinicTests extends AbstractClinicTests { protected String[] getConfigLocations() { return new String[] { "/org/sf/samples/petclinic/hibernate/applicationContext-mocks.xml" }; } }
Slide 82: Training: Simple Bank Management
Slide 83: Training Description • Bank management with the following services:
– Create a new account – Transfer money from one account to another – Get the current balance of an account
• Internal service:
– Update the balance of all accounts (periodically)
Slide 84: Training Description
Client Services DAOs Model DB
Account Management Service (Local & Remote) Client Account DAO (Hibernate & Mock) Account Money Transaction Balance Update DAO (JDBC & Mock) Balance Management Service (Local & Remote)
Unit Tests
Money Management Service (Local & Remote)
Money Transaction DAO (Hibernate & Mock)
Bank DB
Scheduler
Slide 85: Training Description
• Phase 1:
– Implement model, DAO interfaces, service interfaces, service implementations and a basic client. – Use DAO mocks (no DB, Java objects only). – Wire all elements with Spring.
• • • • • •
Phase 2:
– Use Hibernate and JDBC for DAOs (instead of mocks).
Phase 3:
– Add transaction management to services.
Phase 4:
– Add spring-based JUnit tests.
Phase 5:
– Add AOP interceptor for logging.
Phase 6:
– Add Quartz scheduler for periodic balance updating.
Phase 7:
– Access the services remotely instead of locally.
Slide 86: Training: Phase 1
Slide 87: Training Description – Phase 1
• Create an Eclipse project
– Add dependency on external JAR files:
• • • • • • • • • • • • Spring Core (dist/spring.jar) Spring testing infrastructure (dist/spring-mock.jar) J2EE interfaces (lib/j2ee/*.jar) Jakarta Commons (lib/jakarta-commons/*.jar) Hibernate (lib/hibernate/*.jar) Log4J (lib/log4j/*.jar) Quartz (lib/quartz/*.jar) AspectJ (lib/aspectj/*.jar) Dom4J (lib/dom4j/*.jar) Antlr (lib/antlr/*.jar) JUnit (lib/junit/*.jar) JAR file of the database driver. Model DAOs
– – – – Interfaces Mocks Hibernate DAOs JDBC DAOs Interfaces Implementations
–
Create Java packages for:
• •
•
Services
– –
• • • •
Server Client Aspect Test
•
If you want, use a project skeleton to make you work easier…
Slide 88: Training Description – Phase 1
• Create Model Java classes:
– Account
• ID (Integer) • Name (String) • Creation Time (Date) • Balance (Float)
– MoneyTransaction
• ID (Integer) • Source account (Account) • Target account (Account) • Amount (Float) • Creation Time (Date) • Description (String)
Slide 89: Training Description – Phase 1
• Create DAO interfaces:
– AccountDAO
• Account createAccount(String name); • Account findAccount(String name); • List<Account> findAllAccounts();
– MoneyTransactionDAO
• MoneyTransaction createMoneyTransaction( Account sourceAccount, Account targetAccount, Float amount, String description) • Integer countRecentMoneyTransactions( Account account, Date startDate) • List<MoneyTransaction> findMoneyTransactionsByAccount(Account account)
– BalanceUpdateDAO
• updateAccountBalance(Account account)
Slide 90: Training Description – Phase 1 • Create DAO mocks
– AccountDAOMock, MoneyTransactionDAOMock, BalanceUpdateDAOMock – Pure Java implementation – No database usage – Use in-memory objects (e.g., Java map of accounts, map of money transactions, etc.) – One DAO mock can use another DAO mock
Slide 91: Training Description – Phase 1
• Create service interfaces:
– AccountManagement
• Integer createAccount(String name) throws AccountNameInUseException
– Create a new account with the given name while making sure that there’s no account with this name. Return the ID of the created account. Return the pre-calculate balance of the account with the given name.
•
Float getAccountBalance(String name)
–
–
MoneyManagement
• void transferMoney(String sourceAccountName, String targetAccountName, Float amount, String description) throws TooManyMoneyTransactionsException, BalanceTooLowException
– – – Create a money transaction for the accounts of the given names. Make sure that the balance of the user is not too low (e.g., -1000$) Make sure that the number of transactions in the last N days (e.g., 1 day) for each account does not the allowed limit (e.g., 5)
–
BalanceManagement
• void updateBalances()
– Update the balance of all accounts by counting the amounts in all money transactions.
•
Create service implementations:
– Use DAOs (only interfaces, not directly…) for creating, finding and updating Account and MoneyTransaction model entities
Slide 92: Training Description – Phase 1 • Define all beans in a Spring XML file
– (e.g., src/example/client/client1.spring.xml) – Define beans for DAO mocks – Define beans for the services. These beans should reference the DAO beans – XML should start with:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
Slide 93: Training Description – Phase 1
• Write a simple client (‘main’):
– Create a Spring BeanFactory that reads the Spring XML of all beans. Use:
BeanFactory factory = new ClassPathXmlApplicationContext(“example/client/client1.spring.xml”)
– Create AccountManagement, MoneyManagement and BalanceManagement instances using the Spring factory – Use the interfaces for doing something nice and watching everything works
• For example:
– Create 3 accounts: ‘Bank’, A and B. – Transfer money between accounts. – Update the balance of all accounts. – Print the balance of the 3 accounts…
– Is it working?
Slide 94: Training: Phase 2
Slide 95: Training Description – Phase 2
• Create a database schema
– Note: This is a MySQL sample, minor modifications are required for Oracle or other databases.
DROP TABLE IF EXISTS `accounts`; CREATE TABLE `accounts` ( `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL DEFAULT '', `creation_time` DATETIME NOT NULL DEFAULT 0, `balance` FLOAT NOT NULL DEFAULT 0, PRIMARY KEY(`id`), UNIQUE KEY `Index_2` (`name`) ); DROP TABLE IF EXISTS `money_transactions`; CREATE TABLE `money_transactions` ( `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `source_account_id` INTEGER UNSIGNED NOT NULL DEFAULT 0, `target_account_id` INTEGER UNSIGNED NOT NULL DEFAULT 0, `creation_time` DATETIME NOT NULL DEFAULT 0, `amount` FLOAT NOT NULL DEFAULT 0, `description` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY(`id`) );
Slide 96: Training Description – Phase 2
• Implement BalanceUpdateDAO using JDBC:
– Use JdbcDaoSupport as a base class – Use Spring’s JdbcTemplate (getJdbcTemplate()) for running ‘select’ and ‘update’ SQL queries
• Implement AccountDAO and MoneyTransactionDAO using Hibernate:
– Create hbm.xml file with the Hibernate definition of Account and MoneyTransaction model entity – Remember to define correctly the relation between MoneyTransaction and Account (both for sourceAccount and targetAccount) – Define the ID column as an identity generated field – Use HibernateDaoSupport as a base class for the DAOs – Use HibernateTemplate (getHibernateTemplate()) for creating and finding model entities
Slide 97: Training Description – Phase 2
• Define all beans in a Spring XML file:
– Copy client1.spring.xml from phase 1 into client2.spring.xml – Define a datasource bean (while specifying database driver, URL, user name and password) – Define a Hibernate session factory bean (while specifying hbm.xml file location and specific database dialect – Oracle). – Modify DAO bean definitions of Phase 1 to point to the real DAO implementations (while referencing to the define data source and session factory)
Slide 98: Training Description – Phase 2 • Run a simple client:
– Use the same client from phase 1, but modify it to receive as a parameter the name of the Spring XML file to load – Run the client on the new client2.spring.xml file – Is it working the same as in phase 1? – Do you see new records in your DB schema?
Slide 99: Training: Phase 3
Slide 100: Training Description – Phase 3
• Add transaction management definitions in the Spring XML file:
– Copy client2.spring.xml from phase 2 into client3.spring.xml – Add HibernateTransactionManager bean definition – Modify the services (e.g., AccountManagement) to use TransactionProxyFactoryBean
• transactionManager = the HibernateTransactionManager bean • target = AccountManagementImpl bean • transactionAttributes = all methods should use the PROPAGATION_REQUIRES_NEW mode.
Slide 101: Training Description – Phase 3 • Run a simple client:
– Use the same client from phase 2 – Run the client on the new client3.spring.xml file – Is it working like in phase 2? – Try adding a ‘throw new RuntimeException()’ code to AccountDAO after account creation and make sure that the transaction was rolled back and no records were added to DB (in phase 2 the record should exist in DB)
Slide 102: Training: Phase 4
Slide 103: Training Description – Phase 4
• Create a JUnit test using mocks:
– Prepare a mocks.spring.xml file with the DAO mocks definition from phase 1 (copy from client1.spring.xml) – Create a test Java class that extends AbstractDependencyInjectionSpringContextTests
• Define Spring config locations as both client3.spring.xml and mocks.spring.xml (while mocks.spring.xml overrides the beans in client3.spring.xml) • Define setter and getter methods for all services (e.g., AccountManagement) • Add a basic test:
– Run the same code as in the Client class (creating accounts, transferring money and updating balances). – Use the assertEqual utility method for checking that the balances of all accounts are as expected.
– Run the class as a JUnit test and wait for the green light…
Slide 104: Training Description – Phase 4
• Create a JUnit test using DB:
– Create a test Java class that extends AbstractTransactionalDataSourceSpringContextTests
• Define Spring config locations as client3.spring.xml only • Define setter and getter methods for all services (e.g., AccountManagement) • Add a basic test:
– Copy the code from the JUnit test that used mocks (including the assertEqual lines). – Add code that uses getJdbcTemplate for checking that the number of money transaction records in DB is as expected.
– Run the class as a JUnit test and wait for the green light…
Slide 105: Training: Phase 5
Slide 106: Training Description – Phase 5 • Implement a simple logging and performance monitoring POJO:
– Define a public method that should act as an “around” advise. – This method should print (to stdout) the name and arguments of the intercepted method before and after its execution. – In addition, this method should time the execution of the intercepted method and print the time too.
Slide 107: Training Description – Phase 5 • Add logging AOP definitions in the Spring XML file:
– Copy client3.spring.xml from phase 3 into client5.spring.xml – Use <aop:config> XML definition for making the logging method you prepared intercept all public methods of all services (e.g., AccountManagment)
Slide 108: Training Description – Phase 5 • Run a simple client:
– Use the same client from phase 3 – Run the client on the new client5.spring.xml file – Is it working like in phase 3? – Do you see the log lines printed to stdout for each service call?
Slide 109: Training: Phase 6
Slide 110: Training Description – Phase 6
• Define scheduler beans:
– Create a new scheduler.spring.xml file – Define a job detail bean that points to the updateBalances method of the balance management bean – Define a simple trigger that will run the balance updating job details every 5 seconds – Define a scheduler bean that includes the balance updating trigger
• Create a scheduler main Java class:
– Create a Spring BeanFactory using both client5.spring.xml and scheduler.spring.xml (use ClassPathXmlApplicationContext for that) – Create the scheduler bean
• Run the scheduler main class:
– Make sure that balances are updated every 5 seconds (for example, add or modify money transactions and see that the balances are being updates)
Slide 111: Training: Phase 7
Slide 112: Training Description – Phase 7 • Server-side:
– Define server-side Spring beans:
• Create a new server.spring.xml file • Define RMI exporter beans (RmiServiceExporter) for all services (e.g., AccountManagement)
– Create a BankServer Java class:
• Create a Spring BeanFactory using both client5.spring.xml and server.spring.xml (use ClassPathXmlApplicationContext for that)
– Run the BankServer
Slide 113: Training Description – Phase 7 • Client-side:
– Define client-side Spring beans:
• Create a new client7.spring.xml file • Define RMI access beans (RmiProxyFactoryBean) for all services (e.g., AccountManagement)
– Run a simple client:
• Use the same client from phase 3 (& 2) • Run the client on the new client7.spring.xml file • Is it working like in phase 3? • Does it stop working when the BankServer is down?
Slide 114: Summary
Slide 115: Summary
• Spring’s basic concepts are great • Spring is great as a lightweight container • Spring utility classes are very nice • XML configuration of spring is a little bit cumbersome • J2EE evolved and is now a good solution also for simple systems • Always look for existing implementations instead of developing your own • For Web applications, use Ruby on Rails…