Está en la página 1de 26

05/24/08 07:05:35

Article
Home> Articles > Java > JSP

Spring tutorial

This Java Spring Tutorial covers the basics in order to start developing Java Spring examples and applications. Spring can
be used with JSPs and plain Java. Java Spring is also used by some companies as an alternative to EJBs. This tutorial will
help you learn more about Java Spring.

1/26
05/24/08 07:05:35

What is Spring?

Spring is an open source (free) application development framework that makes Java (and primarily J2EE) programming
easier.

Rod Johnson explained his experience and ideas in writing a book (expert one-on-one J2EE Design and Development).
This detailed issues with current J2EE architecture but also provided examples of how to make flexible solutions.

This Spring tutorial is designed for a Java developer to learn how to install, use and integrate Spring into their
applications.

2/26
05/24/08 07:05:35
What are the main concepts for Spring?

There are two central concepts that summarize what Spring does. One is dependency injection and the other is aspect
oriented programming (AOP). For someone learning Spring,these two concepts bring about the most confusion.

Dependency injection
Dependency injection or Inversion of control is based on a best practice technique (design pattern). This technique allows
a part of application to be changed without causing problems in other areas of the application. A design is inflexible
unless it cannot be easily adapted

Aspect Oriented Programming (AOP)


AOP – reduces duplication among classes
Interceptors make it easy to add before and after methods in code snippets.
Useful for caching,logging and security
EHCache,Performance/Tracing interceptors
Acegi for security

3/26
05/24/08 07:05:35
Why use Spring?

Java has many benefits but it is facing increasing competition from advanced in .NET and PHP. One of the problems with
current Java and J2EE development is that it requires too much non-business logic related code.

Java and J2EE development is also progressing especially with open source development such as free libraries and tools.
What this also means is that the knowledge and experience of writing quality applications is also increasing. Maintenance
of applications is the largest phase of most projects and typically in J2EE applications there is a lot of code that deals with
non-business logic. The Spring framework allows developers to focus on developing the main business logic of an
application and be less concerned with remembering if the database connection has been correctly closed.

Spring makes it possible to configure and compose complex applications from simpler components. In Spring,application
objects are composed declaratively,typically in an XML file. Spring also provides much infrastructure functionality
(transaction management,persistent framework integration,etc.),leaving the development of application logic to you.

4/26
05/24/08 07:05:35

Spring architecture

The Spring framework is made up of seven well-defined modules:

Spring is a container that contains and manages the life cycle and configuration of application objects. You can
configure how your beans should be created and how they associate with each other

5/26
05/24/08 07:05:35

As you can see in the figure,all Spring modules are built on top of the core container. The core container
defines how your beans are created,configured and managed

· The core container,where you will find BeanFactory,the heart of any Spring-based application.
BeanFactory is an implementation of the Factory pattern that applies IoC to separate your application
configuration and dependency specifications from the actual application code

· Application context module,where supplies many enterprise services such as e-mail,JNDI access,EJB
integration,remoting,and scheduling. It also supports for internationalization (I18N) messages,application life
cycle events,and validation

· AOP module,supports for aspect-oriented programming. It enables us to interoperate between Spring and
other AOP frameworks.

· JDBC and DAO module,the layer to manage database accesses

· O/R Mapping module,the layer provides hooks into several popular ORM frameworks,including
Hibernate,JDO,iBATIS SQL Maps

· Web module,builds on the application context module,providing a context that is appropriate for web-base
applications.

· MVC framework,Spring has its own a full-featured Model/View/Controller (MVC) for building web
application.

6/26
05/24/08 07:05:35

Installing Spring

Download Spring jars from:

http://www.springframework.org/download

Click the download link to redirect to the Sourceforce file download area

7/26
05/24/08 07:05:35

Extract (Unzip) the Zip file into the standard directory. A similar directory structure as the one below will be created.

8/26
05/24/08 07:05:35

Set classpath browse to the DIST folder where stores all Spring jar files

9/26
05/24/08 07:05:35

Where is Spring in our applications?

The diagram below depicts structure of Spring layer and the way an application use Spring to invoke other business
services:

In above,each business service is registered as a bean in the XML beans descriptor file. When Spring layer receives a
invocation of a service from the application,it will look up the corresponding bean and dispatch the invocation to the
mapped service.

10/26
05/24/08 07:05:35

How to create a bean descriptor XML file?

This section will mention to the ways to declare a business service as a bean

Example for registration a service as bean

<beans>
<bean id=greetingService class=com.visualbuilder.spring.GreetingService/>
</beans>

In this example,class “com.visualbuilder.spring.GreetingService” is registered in Spring under name greetingService.

Example for passing values into properties when initialize bean


Service class:

package com.visualbuilder.spring;
public class ExampleBean
{
private String s;
private int i;

public void setStringProperty(String s) { this.s = s; }


public void setIntegerProperty(int i) { this.i = i; }
}

Bean declaration:

<bean id=exampleBean class=com.visualbuilder.spring.ExampleBean>


<property name=stringProperty><value>Hi!</value></property>
<property name=integerProperty><value>1</value></property>
</bean>

Example for passing property value as an another bean


Service class:

package com.visualbuilder.spring;
public class ExampleBean
{
private AnotherBean beanOne;
private YetAnotherBean beanTwo;

public void setBeanOne(AnotherBean b) { beanOne = b; }


public void setBeanTwo(YetAnotherBean b) { beanTwo = b; }
}

In the XML bean descriptor file:

<bean id=exampleBean class=com.visualbuilder.spring.ExampleBean>


<property name=beanOne><ref bean=anotherExampleBean/></property>
<property name=beanTwo><ref bean=yetAnotherBean/></property>
</bean>

11/26
05/24/08 07:05:35
<bean id=anotherExampleBean class=eg.AnotherBean/>
<bean id=yetAnotherBean class=eg.YetAnotherBean/>

Example for passing parameter value into constructor:


Service class:

package com.visualbuilder.spring;
public class ExampleBean
{
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;

public ExampleBean(AnotherBean b1,YetAnotherBean b2,int i)


{
this.beanOne = b1;
this.beanTwo = b2;
this.i = i;
}
}

In the XML bean descriptor file:

<bean id=exampleBean class=com.visualbuilder.spring.ExampleBean>


<constructor-arg><ref bean=anotherExampleBean/></constructor-arg>
<constructor-arg><ref bean=yetAnotherBean/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>

<bean id=anotherExampleBean class=com.visualbuilder.spring.AnotherBean/>

<bean id=yetAnotherBean class=com.visualbuilder.spring.YetAnotherBean/>

12/26
05/24/08 07:05:35

Spring and Struts

Spring has ability to support to integrate with almost remark Java-based MVC frameworks such as Jakarta Struts,Java
Server Faces,WebWork,and even has its own a MVC framework called Spring MVC framework

Because Jakarta Struts are being used popularly so we would like to introduce the integration between Spring and Struts.
That’s an example for Spring can work well with other Java-based MVC frameworks

13/26
05/24/08 07:05:35
Spring and Struts - Hello World example

We build a Struts web application using the greeting service through Spring like using in Hello world application above

Design and Code


This example is quite simple. It includes only an Action class,GreetingAction,to use Spring application context to look up
the greeting service and request for service. The diagram below shows the sequential interactions between
GreetingAction,Spring application context,and GreetingService

a Struts plug-in that is aware of the Spring application context. Add the following code to your struts-config.xml to
register the plug-in:

<plug-in className=org.springframework.web.struts.ContextLoaderPlugIn>

<set-property property=contextConfigLocation value=/WEB-INF/spring-services.xml/>

</plug-in>

ContextLoaderPlugIn loads a Spring application context (a WebApplication-


Context,to be specific),using the context configuration files listed (comma separated)in its contextConfigLocation
property.

The spring-services.xml declares only bean service with content as in following:

14/26
05/24/08 07:05:35

When receive request,GreetingAction will use Spring application context to look up GreetingService,the code below
shows that:

15/26
05/24/08 07:05:35

How to run
Steps below describe the ways to deploy and run this web application on Tomcat

1. Register GreetingService as a common service on Tomcat by copying greetings.jar file into


$CATALINA_HOME/commons/endorsed,figure below is for example:

16/26
05/24/08 07:05:35

2. Deploy the web application by copying it into Tomcat web folder:

3. Open web browser and go to the link below:

17/26
05/24/08 07:05:35

18/26
05/24/08 07:05:35

Spring data access overview

Spring provides a unique data access abstraction,including a simple and productive JDBC framework.

Spring data access architecture also integrates with TopLink,Hibernate,JDO,and other O/R mapping solutions

In the figure,data accessing in an application is included in a separate layer called DAO

Spring DAO Support classes provide ability to acquire DAO implementations. They also include the DAO classes
extended from DAOSupport to integrate to other database broker system. Each DAO class is used as a bridge to integrate
to a special database broker system,as in the figure below:

19/26
05/24/08 07:05:35

DataSources
In order to execute any JDBC operation on a database,you need a Connection. In Spring DAO,Connection objects are
obtained through a DataSource.

DataSource contains database accessing information and is assigned to Spring DAO Support classes before using these
DAO classes to operate database

DataSourse is declared as a bean in Spring descriptor XML file,for example:

JNDIObjectFactoryBean as DataSource to access via JNDI:

<bean id=dataSource class=org.springframework.jndi.JndiObjectFactoryBean>


<property name=jndiName>
<value>java:comp/env/jdbc/myDatasource</value>
</property>
</bean>

DriverManagerDataSource as DataSource to access via JDBC:

<bean id=myDataSource class=org.springframework.jdbc.datasource.DriverManagerDataSource>

20/26
05/24/08 07:05:35
<property name=driverClassName>
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
</property>

<property name=url>
<value>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Hibernate_books</value>
</property>

<property name=username><value>sa</value></property>
<property name=password><value>sa</value></property>
</bean>

Using DataSource
DataSource is assigned to DAO Support classes through different ways,base on kind of database broker system

Content of the Spring XML descriptor bean files show the way of how a DataSource is assigned to DAO Support.
Following is an example for Hibernate:

With Hibernate,LocalSessionFactoryBean is to store DataSource. The LocalSessionFactoryBean then is passed into


Hibernate DAO Integration in sessionFactory property. In this case,BookService class is a direct subclass of Hibernate
DAO Integration.

21/26
05/24/08 07:05:35

22/26
05/24/08 07:05:35
Spring data access example using Hibernate

This example is web application running as a book search engine. Techniques used are Struts,Spring,and Hibernate.

Hibernate overview
Hibernate is a powerful,high performance object/relational persistence and query service. Hibernate lets you develop
persistent classes following object-oriented idiom – including association,inheritance,polymorphism,composition and
collections. Hibernate allows you to express queries in its own portable SQL extension (HQL),as well as in native SQL.

For more information,go to the home site of Hibernate at


http://www.hibernate.org

Hibernate allows you map data tables to objects and use these object for data operation instead of accessing directly to
data tables,as description below:

Design and code


Architecture of the example looks as:

In there:
• Struts layer controls request
• Hibernate layer accesses real database
• Spring layer register Hibernate services as beans so Struts layer can use them
We created the Spring.hibernate.bean.xml file to declare Hibernate data service as below:

23/26
05/24/08 07:05:35

You can see two extend Spring classes: BookService and CategoryService were declared as beans: bookService and
categoryService

How to deploy and run


Before doing that,must ensure your classpath environment variable point to Spring and Hibernate lib folder.

The simplest way is to copy all jar files of Spring and Hibernate lib folders to the lib folder of the web application. The
figure below shows that the web lib folder contains all lib jar files of Spring and Hibernate:

24/26
05/24/08 07:05:35

25/26
05/24/08 07:05:35

Next Steps

Thank you for reading the Java Spring Tutorial.

We are constantly adding tutorials to the site,so be sure to come back or sign up in the Java group to get notified of
updates.

Check out our other popular tutorials:

JSP Tutorial

Struts Tutorial

Java Hibernate Tutorial

Java Web Component Tutorial

JSP Design Tutorial

As we wish to improve our tutorials we want to know what went well or can be improved. Let us know your comments or
feedback.

See you again!

VisualBuilder Team.

Date entered : 27th May 2007


Rating :No Rating
Submitted by : visualbuilder

Copyright Visualbuilder.com 1999-2006


Document created date: 24 May 2008

26/26

También podría gustarte