Sie sind auf Seite 1von 27

05/24/08 07:05:35

Article Home> Articles > Java > JSP Spring tutorial This Java Spring Tutorial co
vers the basics in order to start developing Java Spring examples and applicatio
ns. Spring can be used with JSPs and plain Java. Java Spring is also used by som
e companies as an alternative to EJBs. This tutorial will help you learn more ab
out Java Spring.
1/26
05/24/08 07:05:35 What is Spring? Spring is an open source (free) application de
velopment 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 architectu
re but also provided examples of how to make flexible solutions. This Spring tut
orial is designed for a Java developer to learn how to install, use and integrat
e Spring into their applications.
2/26
05/24/08 07:05:35 What are the main concepts for Spring? There are two central c
oncepts that summarize what Spring does. One is dependency injection and the oth
er is aspect oriented programming (AOP). For someone learning Spring,these two c
oncepts 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 applic
ation 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 Intercep
tors make it easy to add before and after methods in code snippets. Useful for c
aching,logging and security EHCache,Performance/Tracing interceptors Acegi for s
ecurity
3/26
05/24/08 07:05:35 Why use Spring? Java has many benefits but it is facing increa
sing 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 relat
ed code. Java and J2EE development is also progressing especially with open sour
ce development such as free libraries and tools. What this also means is that th
e knowledge and experience of writing quality applications is also increasing. M
aintenance of applications is the largest phase of most projects and typically i
n J2EE applications there is a lot of code that deals with non-business logic. T
he Spring framework allows developers to focus on developing the main business l
ogic of an application and be less concerned with remembering if the database co
nnection has been correctly closed. Spring makes it possible to configure and co
mpose complex applications from simpler components. In Spring,application object
s are composed declaratively,typically in an XML file. Spring also provides much
infrastructure functionality (transaction management,persistent framework integ
ration,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 w
ell-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 t
op 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 he
art of any Spring-based application. BeanFactory is an implementation of the Fac
tory pattern that applies IoC to separate your application configuration and dep
endency specifications from the actual application code · Application context modu
le,where supplies many enterprise services such as e-mail,JNDI access,EJB integr
ation,remoting,and scheduling. It also supports for internationalization (I18N)
messages,application life cycle events,and validation · AOP module,supports for as
pect-oriented programming. It enables us to interoperate between Spring and othe
r 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 con
text module,providing a context that is appropriate for web-base applications. · M
VC 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.spring
framework.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 st
ructure 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 descript
or file. When Spring layer receives a invocation of a service from the applicati
on,it will look up the corresponding bean and dispatch the invocation to the map
ped service.
10/26
05/24/08 07:05:35 How to create a bean descriptor XML file? This section will me
ntion to the ways to declare a business service as a bean Example for registrati
on a service as bean <beans> <bean id=greetingService class=com.visualbuilder.sp
ring.GreetingService/> </beans> In this example,class “com.visualbuilder.spring.Gr
eetingService” is registered in Spring under name greetingService. Example for pas
sing values into properties when initialize bean Service class: package com.visu
albuilder.spring; public class ExampleBean { private String s; private int i; pu
blic void setStringProperty(String s) { this.s = s; } public void setIntegerProp
erty(int i) { this.i = i; } } Bean declaration: <bean id=exampleBean class=com.v
isualbuilder.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; p
rivate YetAnotherBean beanTwo; public void setBeanOne(AnotherBean b) { beanOne =
b; } public void setBeanTwo(YetAnotherBean b) { beanTwo = b; } } In the XML bea
n descriptor file: <bean id=exampleBean class=com.visualbuilder.spring.ExampleBe
an> <property name=beanOne><ref bean=anotherExampleBean/></property> <property n
ame=beanTwo><ref bean=yetAnotherBean/></property> </bean> 11/26
05/24/08 07:05:35 <bean id=anotherExampleBean class=eg.AnotherBean/> <bean id=ye
tAnotherBean class=eg.YetAnotherBean/>
Example for passing parameter value into constructor: Service class: package com
.visualbuilder.spring; public class ExampleBean { private AnotherBean beanOne; p
rivate 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.sp
ring.ExampleBean> <constructor-arg><ref bean=anotherExampleBean/></constructor-a
rg> <constructor-arg><ref bean=yetAnotherBean/></constructor-arg> <constructor-a
rg><value>1</value></constructor-arg> </bean> <bean id=anotherExampleBean class=
com.visualbuilder.spring.AnotherBean/> <bean id=yetAnotherBean class=com.visualb
uilder.spring.YetAnotherBean/>
12/26
05/24/08 07:05:35 Spring and Struts Spring has ability to support to integrate w
ith almost remark Java-based MVC frameworks such as Jakarta Struts,Java Server F
aces,WebWork,and even has its own a MVC framework called Spring MVC framework Be
cause 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,G
reetingAction,to use Spring application context to look up the greeting service
and request for service. The diagram below shows the sequential interactions bet
ween GreetingAction,Spring application context,and GreetingService
a Struts plug-in that is aware of the Spring application context. Add the follow
ing code to your struts-config.xml to register the plug-in: <plug-in className=o
rg.springframework.web.struts.ContextLoaderPlugIn> <set-property property=contex
tConfigLocation value=/WEB-INF/spring-services.xml/> </plug-in>
ContextLoaderPlugIn loads a Spring application context (a WebApplicationContext,
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 g
reetings.jar file into $CATALINA_HOME/commons/endorsed,figure below is for examp
le:
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 acce
ss abstraction,including a simple and productive JDBC framework. Spring data acc
ess architecture also integrates with TopLink,Hibernate,JDO,and other O/R mappin
g solutions
In the figure,data accessing in an application is included in a separate layer c
alled DAO Spring DAO Support classes provide ability to acquire DAO implementati
ons. 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 Conn
ection. In Spring DAO,Connection objects are obtained through a DataSource. Data
Source contains database accessing information and is assigned to Spring DAO Sup
port classes before using these DAO classes to operate database DataSourse is de
clared as a bean in Spring descriptor XML file,for example: JNDIObjectFactoryBea
n as DataSource to access via JNDI: <bean id=dataSource class=org.springframewor
k.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.DriverManagerDat
aSource>
20/26
05/24/08 07:05:35 <property name=driverClassName> <value>com.microsoft.jdbc.sqls
erver.SQLServerDriver</value> </property> <property name=url> <value>jdbc:micros
oft:sqlserver://localhost:1433;DatabaseName=Hibernate_books</value> </property>
<property name=username><value>sa</value></property> <property name=password><va
lue>sa</value></property> </bean> Using DataSource DataSource is assigned to DAO
Support classes through different ways,base on kind of database broker system C
ontent 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 LocalSessionF
actoryBean then is passed into Hibernate DAO Integration in sessionFactory prope
rty. In this case,BookService class is a direct subclass of Hibernate DAO Integr
ation.
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 objec
t/relational persistence and query service. Hibernate lets you develop persisten
t classes following object-oriented idiom – including association,inheritance,poly
morphism,composition and collections. Hibernate allows you to express queries in
its own portable SQL extension (HQL),as well as in native SQL. For more informa
tion,go to the home site of Hibernate at http://www.hibernate.org Hibernate allo
ws you map data tables to objects and use these object for data operation instea
d 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 • S
pring 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 decl
ared as beans: bookService and categoryService How to deploy and run Before doin
g that,must ensure your classpath environment variable point to Spring and Hiber
nate lib folder. The simplest way is to copy all jar files of Spring and Hiberna
te 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 i
n the Java group to get notified of updates. Check out our other popular tutoria
ls: JSP Tutorial Struts Tutorial Java Hibernate Tutorial Java Web Component Tuto
rial JSP Design Tutorial As we wish to improve our tutorials we want to know wha
t went well or can be improved. Let us know your comments or feedback. See you a
gain! 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

Das könnte Ihnen auch gefallen