P. 1
What does Spring do

What does Spring do

|Views: 157|Likes:
Published by babith

More info:

Published by: babith on Feb 08, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

11/14/2011

pdf

text

original

Sections

  • What does Spring do?
  • JDBC abstraction and data access exception hierarchy
  • O/R mapping integration
  • AOP
  • MVC web framework
  • Implementing EJBs
  • Testing
  • Who's using Spring?
  • Summary
  • Spring MVC Introduction
  • How Spring MVC Works?
  • Controllers in Spring MVC
  • Starting the development using Spring MVC Framework
  • Introduction to the Spring Framework
  • Installing Spring Framework
  • Spring Injection Example
  • Inheritance in Spring
  • Spring Hello World Application
  • Calling Constructor in Spring
  • init Method in Spring
  • Bean life cycle in spring

What does Spring do?

Spring provides a lot of functionality, so I'll quickly review each major area in turn. Mission statement Firstly, let's be clear on Spring's scope. Although Spring covers a lot of ground, we have a clear vision as to what it should and shouldn't address. Spring's main aim is to make J2EE easier to use and promote good programming practice. It does this by enabling a POJObased programming model that is applicable in a wide range of environments. Spring does not reinvent the wheel. Thus you'll find no logging packages in Spring, no connection pools, no distributed transaction coordinator. All these things are provided by open source projects (such as Commons Logging, which we use for all our log output, or Commons DBCP), or by your application server. For the same reason, we don't provide an O/R mapping layer. There are good solutions to this problem such as TopLink, Hibernate and JDO. Spring does aim to make existing technologies easier to use. For example, although we are not in the business of low-level transaction coordination, we do provide an abstraction layer over JTA or any other transaction strategy. Spring doesn't directly compete with other open source projects unless we feel we can provide something new. For example, like many developers, we have never been happy with Struts, and felt that there was room for improvement in MVC web frameworks. (With Spring MVC adoption growing rapidly, it seems that many agree with us.) In some areas, such as its lightweight IoC container and AOP framework, Spring does have direct competition, but Spring was a pioneer in those areas. Spring benefits from internal consistency. All the developers are singing from the same hymn sheet, the fundamental ideas remaining faithful to those of Expert Oneon-One J2EE Design and Development. And we've been able to use some central concepts, such as Inversion of Control, across multiple areas. Spring is portable between application servers. Of course ensuring portability is always a challenge, but we avoid anything platform-specific or non-standard in the developer's view, and support users on WebLogic, Tomcat, Resin, JBoss, Jetty, Geronimo, WebSphere and other application servers. Spring's non-invasive, POJO, approach enables us to take advantage of environment-specific features without sacrificing portability, as in the case of enhanced WebLogic transaction management functionality in Spring 1.2 that uses BEA proprietary APIs under the covers. Inversion of control container The core of Spring is the org.springframework.beans package, designed for working with JavaBeans. This packagetypically isn't used directly by users, but underpins much Spring functionality.

1

The next higher layer of abstraction is the bean factory. A Spring bean factory is a generic factory that enables objects to be retrieved by name, and which can manage relationships between objects. Bean factories support two modes of object: • • Singleton: in this case, there's one shared instance of the object with a particular name, which will be retrieved on lookup. This is the default, and most often used, mode. It's ideal for stateless service objects. Prototype or non-singleton: in this case, each retrieval will result in the creation of an independent object. For example, this could be used to allow each caller to have its own distinct object reference.

Because the Spring container manages relationships between objects, it can add value where necessary through services such as transparent pooling for managed POJOs, and support for hot swapping, where the containerintroduces a level of indirection that allows the target of a reference to be swapped at runtime without affecting callers and without loss of thread safety. One of the beauties of Dependency Injection (discussed shortly) is that all this is possible transparently, with no API involved. As org.springframework.beans.factory.BeanFactory is a simple interface, it can be implemented in different ways. The BeanDefinitionReader interface separates the metadata format from BeanFactory implementations themselves, so the generic BeanFactory implementations Spring provides can be used with different types of metadata. You could easily implement your own BeanFactory or BeanDefinitionReader, although few users find a need to. The most commonly used BeanFactory definitions are: • • XmlBeanFactory. This parses a simple, intuitive XML structure defining the classes and properties of named objects. We provide a DTD to make authoring easier. DefaultListableBeanFactory: This provides the ability to parse bean definitions in properties files, and create BeanFactories programmatically.

Each bean definition can be a POJO (defined by class name and JavaBean initialisation properties or constructorarguments), or a FactoryBean. The FactoryBean interface adds a level of indirection. Typically this is used to create proxied objects using AOP or other approaches: for example, proxies that add declarative transaction management. This is conceptually similar to EJB interception, but works out much simpler in practice, and is more powerful. BeanFactories can optionally participate in a hierarchy, "inheriting" definitions from their ancestors. This enables the sharing of common configuration across a whole application, while individual resources such as controller servlets also have their own independent set of objects. This motivation for the use of JavaBeans is described in Chapter 4 of Expert One-onOne J2EE Design and Development, which is available on the ServerSide as a free PDF (/articles/article.tss?l=RodJohnsonInterview).

2

Through its bean factory concept, Spring is an Inversion of Control container. (I don't much like the term container, as it conjures up visions of heavyweight containers such as EJB containers. A Spring BeanFactory is a container that can be created in a single line of code, and requires no special deployment steps.) Spring is most closely identified with a flavor of Inversion of Control known as Dependency Injection--a name coined by Martin Fowler, Rod Johnson and the PicoContainer team in late 2003. The concept behind Inversion of Control is often expressed in the Hollywood Principle: "Don't call me, I'll call you." IoC moves the responsibility for making things happen into the framework, and away from application code. Whereas your code calls a traditional class library, an IoC framework calls your code. Lifecycle callbacks in many APIs, such as the setSessionContext() method for session EJBs, demonstrate this approach. Dependency Injection is a form of IoC that removes explicit dependence on container APIs; ordinary Java methods are used to inject dependencies such as collaborating objects or configuration values into application object instances. Where configuration is concerned this means that while in traditional container architectures such as EJB, a component might call the container to say "where's object X, which I need to do my work", with Dependency Injection thecontainer figures out that the component needs an X object, and provides it to it at runtime. The container does this figuring out based on method signatures (usually JavaBean properties or constructors) and, possibly, configuration data such as XML. The two major flavors of Dependency Injection are Setter Injection (injection via JavaBean setters); andConstructor Injection (injection via constructor arguments). Spring provides sophisticated support for both, and even allows you to mix the two when configuring the one object. As well as supporting all forms of Dependency Injection, Spring also provides a range of callback events, and an API for traditional lookup where necessary. However, we recommend a pure Dependency Injection approach in general. Dependency Injection has several important benefits. For example: • Because components don't need to look up collaborators at runtime, they're much simpler to write and maintain. In Spring's version of IoC, components express their dependency on other components via exposing JavaBean setter methods or through constructor arguments. The EJB equivalent would be a JNDI lookup, which requires the developer to write code that makes environmental assumptions. For the same reasons, application code is much easier to test. For example, JavaBean properties are simple, core Java and easy to test: simply write a self-contained JUnit test method that creates the object and sets the relevant properties. A good IoC implementation preserves strong typing. If you need to use a generic factory to look up collaborators, you have to cast the results to the desired type. This isn't a major problem, but it is inelegant. With IoC you express strongly typed dependencies in your code and the framework is responsible for type casts. This means that type mismatches will be raised as

3

Most business objects don't depend on IoC container APIs. In my experience and that of Spring users. This is analogous to. This makes it easy to use legacy code. Spring BeanFactories are very lightweight. which limits its functionality in comparison with Spring. the environmental assumptions may not be obvious without reading the code (complicating testing and reducing deployment flexibility). but Spring also provides unique support for instantiating objects from static factory methods or even methods on other objects managed by the IoC container. Unlike EJBs.or outside any framework without code changes. This means that your business objects can potentially be run in different Dependency Injection frameworks . With a Dependency Injection approach. Spring users often configure the Jakarta Commons DBCP DataSource as a Spring bean: there's no need to write any custom code to do this. and is a key reason that Spring is so internally consistent.• • errors when the framework configures the application. although it's only recently made prime time in the J2EE community. in this minimization of dependency of application code on container.0 will provide a basic DI capability as well. than a layer of local session beans. This ability to instantiate a container almost instantly in any tier of an application can be very valuable. especially. For example. one or more BeanFactories provide a well-defined layer of business objects. Dependency Injection is not a new concept. if an application class tries to load a properties file or connect to a database on instantiation. but much simpler (yet more powerful). dependencies are explicit. Spring is also unique among IoC containers in that it uses IoC as a basic concept throughout a full-featured framework. It does not use metadata outside Java code. the objects in this 4 . There are alternative DI containers: notably. as well as standalone Swing applications. Dependencies are explicit. EJB 3. PicoContainer and HiveMind. Users have successfully used them inside applets. Dependency Injection is unlike traditional container architectures. HiveMind is conceptually more similar to Spring (also aiming at more than just IoC). PicoContainer is particularly lightweight and emphasizes the expression of dependencies through constructors rather than JavaBean properties. Dependency Injection--brings to application code. For example. you don't have to worry about class cast exceptions in your code. and evident in constructor or JavaBean properties. The Spring BeanFactory concept is used throughout Spring. We say that an IoC container isn't invasive: using it won't invade your code with dependency on its APIs. Existing JavaBeans or objects with multiargument constructors work particularly well. and easy to use objects either inside or outside the IoC container. Most importantly for application developers. (They also work fine within an EJB container. it's hard to overemphasize the benefits that IoC--and. Almost any POJO can become a component in a Spring bean factory. such as EJB. This last point deserves emphasis.) There are no special deployment steps and no detectable startup time associated with the container itself (although certain objects configured by the container may of course take time to initialize). although it lacks the comprehensive scope of the Spring project or the same scale of user community.

as it offers JavaBean-style configuration.dbcp. which configures three application objects with relationships commonly seen in J2EE applications: • • • A J2EE DataSource A DAO that uses the DataSource A business object that uses the DAO in the course of its work In the following example. which will be the name that we'll use this bean with in our code. (ComboPooledDataSource from the C3PO project is also an excellent option. like many other existing classes. A Spring ApplicationContext is a subinterface of BeanFactory. The <beans> element contains one or more <bean> definitions. supporting internationalization An eventing mechanism. which is usable even for values that are problematic in XML attributes. We must also specify the id.2. It's a convenient alternative to the <value> subelement. to avoid the need for BasicDataSource to implement any Spring interface. can easily be used in a Spring bean factory.) BasicDataSource.commons. and their relationships managed by the owning factory.mysql. Let's look at a simple example.layer can be interrelated.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com. <beans> <bean id="myDataSource" class="org. Having a well-defined layer of business objects is very important to a successful architecture. (This shortcut was introduced in Spring 1.jdbc.apache.) Spring uses the standard JavaBean 5 . allowing application objects to publish and optionally register to be notified of events Automatic recognition of special application-specific or generic bean definitions that customize container behavior Portable file and resource access XmlBeanFactory example Spring users normally configure their applications in XML "bean definition" files. The close method that needs to be called on shutdown can be registered via Spring's "destroy-method" attribute.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mydb" /> <property name="username" value="someone" /> </bean> All the properties of BasicDataSource we're interested in are Strings. which provides support for: • • • • Message lookup. we use a BasicDataSource from the Jakarta Commons DBCP project. so we specify their values with the "value" attribute. We normally specify the class and properties of each bean definition. The root of a Spring XML bean definition document is a <beans> element.

if we didn't want to code these relationships explicitly: <bean id="exampleBusinessObject" class="example.PropertyEditor mechanism to convert String representations to other types if necessary. as in this example.ExampleBusinessObject" autowire="byType"> <property name="exampleParam" value="10" /> </bean> With this usage. Now we define the DAO. Autowire support has the advantage of reducing the volume of configuration. or more than one. it may be 6 . We still need to set the exampleParam property.ExampleBusinessObject"> <property name="dataAccessObject"><ref bean="exampleDataAccessObject"/></property> <property name="exampleParam"><value>10</value></property> </bean> </beans> Relationships between objects are normally set explicitly in configuration. Relationships between beans are specified using the "ref" attribute or <ref> element: <bean id="exampleDataAccessObject" class="example. The limitation with this . bean of the required type in the present BeanFactory. (Spring also offers an optional dependency check for explicit configuration. However. unsatisfied dependencies can be caught when the factory is initialized. where it figures out the dependencies between beans. Spring will work out that the dataSource property of exampleBusinessObject should be set to the implementation of DataSource it finds in the present BeanFactory. Spring also provides what we call "autowire" support. On the positive side.as with PicoContainer . I've used the subelement syntax familiar to those who've used Spring prior to 1.is that if there are multiple beans of a particular type it's impossible to work out which instance a dependency of that type should be resolved to. as it's not a reference. We consider this to be a Good Thing in most cases. which can achieve this goal.ExampleDataAccessObject"> <property name="dataSource" ref="myDataSource" /> </bean> The business object has a reference to the DAO. so if you add an additional constructor argument of JavaBean property. It also means that the container can learn about application structure using reflection. In this case.2: <bean id="exampleBusinessObject" class="example. It's an error if there is none. which has a bean reference to the DataSource.) We could use the autowire feature as follows in the above example. and an int property (exampleParam).

or a test data source. via setDataSource() and setExampleParam() calls. public void setDataAccessObject(ExampleDataAccessObject dao) { this. public class ExampleBusinessObject implements MyBusinessObject { private ExampleDataAccessObject dao. Note that the JavaBean properties are not declared on the business interface callers will work with. So long as you have a no-args constructor. you're free to define other constructors taking multiple properties if you want to support programmatic construction in a single line of code. a Spring BeanFactory is not invasive: you don't normally need to code awareness of it into application objects. For example. Note that there are no Spring dependencies in the code listing below. Just instantiate it with its default constructor.jndi. Unlike an EJB container. private int exampleParam. Externalizing relationships from Java code has an enormous benefit over hard coding it.springframework. for example in a test environment.dao = dao. } public void myBusinessMethod() { // do stuff using dao } } Note the property setters. They're an implementation detail. These are invoked by Spring before the object is used. as it's possible to change the XML file without changing a line of Java code. we could simply change the myDataSource bean definition to refer to a different bean class to use an alternative connection pool.JndiObjectFactoryBean"> <property name="jndiName" value="jdbc/myDataSource" /> </bean> Now let's look at the Java code for the example business object. Reusing one outside of a Spring application context is easy. which correspond to the XML references in the bean definition document. The tradeoffs around autowiring need to be evaluated carefully. <bean id="myDataSource" class="org. There would be no impact on Java code or any other bean definitions. and set its properties manually. as follows. Such application beans do not need to depend on Spring: They don't need to implement any Spring interfaces or extend Spring classes: they just need to observe JavaBeans naming convention. We could use Spring's JNDI location FactoryBean to get a datasource from an application server in a single alternative XML stanza.exampleParam = exampleParam. } public void setExampleParam(int exampleParam) { this. We can easily "plug in" different 7 .successfully populated without any need to change configuration.

a form of IoC in which the container implements an abstract method or overrides a concrete method to inject a dependency. The Spring Rich project (a framework for simplifying the development of Swing applications using Spring) demonstrates how 8 . it can be useful to avoid an explicit container dependency when looking up a new object instance for each invocation. in which a property element contains an anonymous bean definition not visible at top-level scope Post processors: special bean definitions that customize container behavior Method Injection. with the method implementation being backed by a SQL query in one environment and a fil system read in another. or to allow configuration to vary over time--for example. WebWork or other web frameworks. Spring provides the ability to instantiate such a context through a listener or servlet without dependence on the Spring MVC framework. maps and java.implementing classes that have different bean properties without affecting connected objects or calling code. A Servlet: Each controller servlet in the Spring MVC framework has its own application context. However. so it can also be used in Struts. derived from the root (application-wide) application context. it's trivial to instantiate a BeanFactory programmatically if we wish. Other advanced container capabilities include: • • • Inner beans. • • These hooks provided by the J2EE specification generally avoid the need to use a Singleton to bootstrap a bean factory. This code will work outside an application server: it doesn't even depend on J2EE.getBean("exampleBusinessObject"). Of course Spring XML bean factories have many more capabilities than described here. getClass())). Bean factories and application contexts are often associated with a scope defined by the J2EE server or web container. This is a more rarely used form of Dependency Injection than Setter or Constructor Injection.xml". such as: • The Servlet context. For example. It's also easy to accomplish this with Struts or another MVC framework. However. and properties for which you have a JavaBeans PropertyEditor. but this should give you a feel for the basic approach. EJB: Spring provides convenience superclasses for EJB that simplify EJB authoring and provide a BeanFactory loaded from an XML document in the EJB Jar file. In the Spring MVC framework. Spring can handle lists.Properties. as the Spring IoC container is pure Java. MyBusinessObject mbo = (MyBusinessObject) bf. an application context is defined for each web application containing common objects.util. As well as simple properties. we could create the bean factory and get a reference to the business object defined above in the following three lines of code: XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("myFile.

When Spring first obtains a connection from a DataSource it examines the metadata to determine the database product.Spring can be used outside a J2EE environment. or server-side. Spring's data access exceptions are not JDBCspecific. application code can concentrate on issuing the appropriate SQL and extracting results. The relatively uninformative SQLException. • Spring addresses these problems in two ways: • By providing APIs that move tedious and error-prone exception handling out of application code into the framework. Note that none of the exceptions shown here is JDBC-specific. and need not worry about proprietary SQLState or error codes. JDBC does not offer an exception hierarchy. By providing a meaningful exception hierarchy for your application code to work with in place of SQLException. There are JDBC-specific subclasses of some of these exceptions. Spring provides two levels of JDBC abstraction API. as do Spring's integration testing features.springframework. Dependency Injection and the related functionality is too general and valuable to be confined to a J2EE. was the problem a deadlock or invalid SQL? .core package.springframework. Statements and (most importantly) Connections are closed after use. JDBC offers fairly good abstraction from the underlying database. environment. Finding out what actually went wrong .and 9 . discussed later in this article.DataAccessException.for example. but calling code is generally abstracted wholly away from dependence on JDBC: an essential if you wish to use truly API-agnostic DAO interfaces to hide your persistence strategy. The framework takes care of all exception handling. The meaning of these values varies between databases. uses callbacks to move control . but throws SQLException in response to all errors. Thus your code can work with meaningful exceptions. It uses this knowledge to map SQLExceptions to the correct exception in its own hierarchy descended from org.jdbc. but is a painful API to use. • The following UML class diagram illustrates a part of this data access exception hierarchy.involves examining the SQLState value and error code. The first. indicating its sophistication. This means that correct use of JDBC can quickly result in a lot of code. Some of the problemsinclude: • The need for verbose error handling to ensure that ResultSets. It's also a common source of errors.dao. JDBC abstraction and data access exception hierarchy Data access is another area in which Spring shines. so your DAOs are not necessarily tied to JDBC because of the exceptions they may throw. in the org. Connection leaks can quickly bring applications down under load.

but provides an API in which an RDBMS operation . int rowNum) throws SQLException.from application code inside the framework. The example also illustrates the use of bind variables: int youngUserCount = template. The Spring JDBC abstraction has a very low performance overhead beyond standard JDBC. new Object[] { new Integer(25) }).2 million inserts per transaction. This is built on the core JDBC callback functionality. This is a different type of Inversion of Control.NAME FROM USER". return rs. Spring classes that perform such callbacks are called templates.springframework.getString(1). new RowMapper() { public Object mapRow(ResultSet rs. we profiled the performance of a financial application performing up to 1. transaction management (using JTA) and JNDI. The application developer can choose which exceptions.whether query.queryForInt("SELECT COUNT(0) FROM USER WHERE USER.hence error handling and connection acquisition and release . For example. to catch and handle. A query object to return User objects might look like this: class UserQuery extends MappingSqlQuery { 10 . if any.jdbc. such as JDO (acquiring and relinquishing a PersistenceManager).) The higher level JDBC abstraction is in the org. (In one project in 2004. the Spring JdbcTemplate object can be used to perform a SQL query and save the results in a list as follows: JdbcTemplate template = new JdbcTemplate(dataSource). Simple tasks like running SQL functions can be accomplished without a callback. even when working with huge result sets. The mapRow callback method will be invoked for each row of the ResultSet.is modelled as a Java object. List names = template. and the use of Spring facilitated the tuning of batch sizes and other parameters. The JdbcTemplate provides many methods to support different scenarios including prepared statements and batch updates. update or stored procedure . as follows. which I found intuitive and highly usable.AGE < ?".query("SELECT USER. Spring uses a similar callback approach to address several other APIs that involve special steps to acquire and cleanup resources. The overhead of Spring JDBC was minimal. Note that application code within the callback is free to throw SQLException: Spring will catch any exceptions and rethrow them in its own hierarchy.object package. but equally valuable to that used for configuration management. This API was partly inspired by the JDO query API. } }).

Spring enables a stored procedure to be proxied by a Java class with a single business method.setForename(rs.public UserQuery(DataSource datasource) { super(datasource. if we can't connect to the database. Data access exceptions not usually recoverable.jdbc. } // Map a result set row to a Java object protected Object mapRow(ResultSet rs.object package is the StoredProcedure class.setId(rs. All Spring data access exceptions are subclasses of DataAccessException. we can easily do so. Note that if we do want to recover from an unchecked data access exception. but not all applications use optimistic locking. we can write code in a Spring DAO as follows: 11 . declareParameter(new SqlParameter(Types. For example. They are threadsafe. This class can be used as follows: User user = userQuery. For example. you can define an interface that the stored procedure implements.NUMERIC)). One potential exception is optimistic lockingviolations.getString("FORENAME")). We can write code to handle only the recoverable condition. The Spring data access exception hierarchy is based on unchecked (runtime) exceptions. Having worked with Spring on several projects I'm more and more convinced that this was the right decision. "SELECT * FROM PUB_USER_ADDRESS WHERE USER_ID = ?").springframework.getLong("USER_ID")). Another important class in the org. Such objects are often inner classes inside DAOs. If you like.findUser(25). compile(). Letting them propagate to toplevel handlers like the servlet or EJB container is usually more appropriate. so if we do choose to catch all Spring data access exceptions. It's usually bad to be forced to write code to catch fatal exceptions that can't be sensibly handled. if we consider that only an optimistic locking violation is recoverable. user. a particular business object is unlikely to be able to work around the problem. we can still do so. } public User findUser(long id) { // Use superclass convenience method to provide strong typing } } return (User) findObject(id). return user. user. meaning that you can free your application code from depending on the use of a stored procedure at all. unless the subclass does something unusual. int rownum) throws SQLException { User user = new User().

you'll find it easy to implement the DAO pattern without business logic depending on any particular data access API. I used to loathe writing JDBC code. Whatever persistence technology use. Because we're forced to catch the base exception (DataAccessException). we'd need to write the following code. but provide no help in forcing us to deal with the recoverable problem. it was partly inspired by JDO. In practice we find that all this amounts to substantial productivity gains and fewer bugs.applies also to the second. 12 . Your application won't be dependent on RDBMS-specific error handling code. Hibernate switched from checked to unchecked exceptions in version 3. and that code will be clearly focused on the necessary SQL You'll never need to dig through your RDBMS documentation to work out what obscure error code it returns for a bad column name. use unchecked exceptions exclusively. TopLink and JDO. the compiler won't enforce a check for a subclass (OptimisticLockingFailureException).successful persistence frameworks.) JDBC is one of the few data access APIs to use checked exceptions. Spring's use of unchecked data access exceptions is consistent with that of many probably most . now I find that I can focus on the SQL I want to execute. rather than the incidentals of JDBC resource management. for example. So the compiler would force us to write code to handle an unrecoverable problem. Note that we could choose to write this anyway: try { // do work } catch (OptimisticLockingFailureException ex) { // I'm interested in this } catch (DataAccessException ex) { // Fatal. Spring JDBC can help you in several ways: • • • • • • You'll never need to write a finally block again to use JDBC Connection leaks will be a thing of the past You'll need to write less code overall. just rethrow it } One potential objection to the first example .try { // do work } catch (OptimisticLockingFailureException ex) { // I'm interested in this } If Spring data access exceptions were checked.that the compiler can't enforce handling the potentially recoverable exception . (Indeed. You'll benefit from improved portability (compared to raw JDBC) in advanced areas such as BLOB handling and invoking stored procedures that return result sets.

JDBC datasources. Resource management. Spring can transparently create and bind a session to the current thread. to a set of abstracted runtime exceptions. you may find that certain functionality is just not suited to an implemention using your ORM tool. or any other concerns. Thus Spring integrates out of the box with Hibernate (versions 2 and 3). Related code using the ORM tool alone generally needs to use the same "Session" object for efficiency and proper transaction handling. Spring offers efficient.) in case of exceptions is taken care of. Spring allows you to wrap your ORM code with either a declarative. As we discuss later. Spring application contexts can handle the location and configuration of Hibernate SessionFactories. "template" wrapperclass at the Java code level.Spring's JDBC abstraction can be used standalone if desired . without annoying boilerplate catches/throws. This allows you to handle most persistence exceptions. As an added benefit. performance. O/R mapping integration Of course often you want to use O/R mapping. To avoid vendor lock-in. you also get the benefit of being able to use and swap various transaction managers. etc. easy. or an explicit 'template' wrapper class at the Java code level. Its data access architecture allows it to integrate with anyunderlying data access technology. Thus Spring solves many of the usage issues that affect many users of ORM technology. using Spring now can • • • • 13 . or by using an explicit. This makes these values easy to manage and change. instead of the ORM product directly? Spring adds significant value in the following areas: • Session management. and there is no perfect one size fits all solution. transaction semantics are handled for you. in the case of most supported ORM tools. You can still trap and handle exceptions anywhere you need to. Integrated transaction management. Spring and Hibernate are a particularly popular combination. TopLink and other ORM products. as described above. Exception wrapping. without your ORM-related code being affected. Your overall application framework must support this also. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy.you are not forced to use the other parts of Spring. If you may ever need to switch to another implementation for reasons of functionality. Spring can wrap exceptions from the ORM layer. converting them from proprietary (possibly checked) exceptions. which are non-recoverable. and other related resources. AOP method interceptor. Why would you use an ORM product plus Spring. and exception declarations. Alternatively. AOP method interceptor approach. using either a declarative. This is useful for handling functionality not amenable to ORM. JDO (versions 1 and 2). In either case. and safe handling of units of work such as Hibernate or TopLink Sessions. meaning that you can perform some operations with JDBC within a consistent programming model. only in the appropriate layers. rather than use relational data access. Thus it makes sense to decouple your architecture from the tool-specific implementations of your data access object interfaces. JDBCrelated code can fully integrate transactionally with ORM code. and proper transaction handling (rollback. ORM solutions have different performance other characterics.

Spring's transaction abstraction is unique in that it's not tied to JTA or any other transaction management technology. although it is a valuable productivity win in many cases. Spring enables a consistentarchitecture. Actually. we also need to consider transaction management. It provides a high level of control over SQL. Spring has changed that. datasources. with some unique and important benefits. Transaction management Abstracting a data access API is not enough. and transaction strategy. but without the need for an EJB container. Spring uses the concept of a transaction strategy that decouples application code from the underlying transaction infrastructure (such as JDBC). without sacrificing any of the power of your ORM tool. as we'll see. In cases where ORM is not ideally suited. Spring uses this to deliver: • • Programmatic transaction management via a callback template analogous to the JdbcTemplate. You may not even need a high-end application server that provides 14 . Despite the claims of some ORM vendors. but it's a cumbersome API to use directly. Ease of testing. The PetClinic sample application shipped with Spring demonstrates the portability benefits that Spring offers. along with its IoC approach which allow you to easily swap in mapper/DAO objects implementing data-access functionality. through providing variants that use JDBC. even if you mix and match persistence approaches. Spring's PetStore sample application illustrates iBATIS integration. and as a result many J2EE developers used to feel that EJB CMT is the only rational option for transaction management. even without using JTA. Spring's declarative transaction management capability is a semantically compatible superset of EJB CMT. This makes it much easier to isolate and test each piece of persistence-related code in isolation. ORM is not the solution to all problems.• make the eventual switch much easier. TopLink and Apache OJB to implement the persistence layer. which is much easier to use than straight JTA Declarative transaction management analogous to EJB CMT. Spring's inversion of control approach makes it easy to swap the implementations and locations of resources such as Hibernate session factories. make it easy to isolate all ORM-specific code in one area of your application. Hibernate. Spring integrates with SQL Maps out of the box. JTA is the obvious solution. and mapper object implementations (if needed). Spring facilitates a mix-and-match approach to data access. transaction managers. while still automating the creation of mapped objects from query results. You're not interested in XA transactions or two phase commit. Spring's abstraction of your ORM tool's Transactions and Exceptions. you don't need the complexity of JTA. Spring provides its own abstraction for transaction management. Why should you care about this? Isn't JTA the best answer for all transaction management? If you're writing an application that uses only a single database. Spring's simplified JDBC is not the only option: the "mapped statement" approach provided by iBATIS SQL Maps is worth a look. Above all.

Resin. Key AOP concepts supported include: • • • Interception: Custom behaviour can be inserted before or after method invocations against any interface or class. OOP. so there's no risk of vendor lock in. you'll have to rip out all that transaction management code and replace it with JTA transactions. In five or ten years time we will probably have travelled a lot farther on the AOP learning curve and feel comfortable giving AOP a seat at the top table of application design. Jetty. JBoss. It works in either web or EJB container. on the other hand. enabling a standard interceptor to be applied in different applications and code contexts. Static and dynamic pointcuts: Specifying the points in program execution at which interception should take place. to recommend using global JTA transactions exclusively.) 15 . Using the Spring transaction abstraction. This is a deliberate design decision. rather than JDBC or Hibernate. I have always felt that field interception violates encapsulation. If you ever need to work with multiple data sources. AOP Since 2003 there has been much interest in applying AOP solutions to those enterprise concerns. The first goal of Spring's AOP support is to provide J2EE services to POJOs. however. This is a configuration change. Thus. you only have to reconfigure Spring to use a JTA. But. Spring AOP supports method interception. Pointcuts are defined separately from interceptors. This is similar to "around advice" in AspectJ terminology. Introduction: Specifying that an advice should cause an object to implement additional interfaces. and has been used successfully in WebLogic. not a code change. I prefer to think of AOP as complementing. Imagine you decide to avoid the overhead of JTA by using JDBC or Hibernate transactions directly. Spring enables you to write applications that can scale down as well as up. Spring AOP is portable between application servers. Orion and many other application servers and web containers. transaction strategy and you're done. Spring supports both stateful (one instance per advised object) and stateless interceptors (one instance for all advice). dynamic pointcuts may also consider method arguments at the point where they are evaluated. rather than conflicting with. including myself. (At that point languagebased solutions such as AspectJ may be far more attractive than they are today. which have traditionally been addressed by EJB. you don't want to have to rewrite your code should you ever have to work with multiple data sources. effectively ruling out using a simple web container such as Tomcat for transactional applications. Spring does not support field interception.these things. such as transaction management. This canamount to mixin inheritance. Static pointcuts concern method signatures. This isn't very attractive and led most writers on J2EE. Tomcat.

level. Depending on the transaction strategy. Spring integrates with AspectJ. application developers often want a transaction to roll back on any exception. Thus AspectJ aspects can depend on any Spring-managed objects. it is possible to use multiple instances of the same class with different advice. in addition to the propagation modes specified by EJB CMT (which Spring supports with identical semantics to EJB). other types of Throwable and "system" exceptions). as well as unchecked exceptions. Default behaviour is as with EJB. and can deliver declarative transaction management on any POJO. The integration with the forthcoming AspectJ 5 release is still more exciting. so you don't need to propagate a context object such as an EJBContext to ensure rollback. providing the ability to seamlessly include AspectJ aspects into Spring applications . and is not enforced by the framework.1 it has been possible to dependency inject AspectJ aspects using the Spring IoC container. Spring was the first AOP framework to implement the AOP Alliance interfaces (www. Hibernate or any other API offering transaction management. Perhaps the commonest use of Spring AOP is for declarative transaction management. using ThreadLocal variables. These represent an attempt to define interfaces allowing interoperability of interceptors between AOP frameworks.Spring implements AOP using dynamic proxies (where an interface exists) or CGLIB byte code generation at runtime (which enables proxying of classes). which creates a dependence on the Spring transaction API (as EJB programmatic rollback does on the EJBContext). just like any Java class. We provide static methods for this. based on an annotation-driven pointcut. with AspectJ set to provide the ability to dependency inject any POJO using Spring. Since Spring 1. but you can specify automatic rollback on checked. rather than class loader. or in a standalone environment. Both these approaches work in any application server. This builds on the transaction abstraction described above. but this is a matter of good programming practice. Whereas EJB will not automatically roll back a transaction on an uncaught application exception (only on unchecked exceptions. the underlying mechanism can be JTA.sourceforge. We recommend that business objects implementinterfaces. This has the important benefit of minimizing the need for programmatic rollback. Because Spring advises objects at instance. You can define rollback rules declaratively. Programmatic rollback can be achieved within a transactional POJO through using the Spring transaction API.net/projects/aopalliance). Thus. for example. if you have • • 16 . The following are the key differences from EJB CMT: • • Transaction management can be applied to any POJO. Because the underlying Spring transaction abstraction supports savepoints if they are supported by the underlying transaction infrastructure. Spring transaction management allows you to specify declaratively which exceptions and subclasses should cause automatic rollback. or use unadvised instances along with advised instances. JDBC. Spring's declarative transaction management can support nestedtransactions.

and reflects Spring's architectural approach.aop. (Multiple proxy methods are supported. rather than Spring's capabilities. where the complexity of security checks required is beyond the capability of the standard J2EE security infrastructure. Debugging and profiling aspects for use during development Aspects that apply consistent exception handling policies in a single place Interceptors that send emails to alert administrators or users of unusual scenarios • • • Application-specific aspects can be a powerful way of removing the need for boilerplate code across many methods. but it can be very useful. Whether or not you choose to do this depends on your level of comfort with AOP concepts.ITestBean</value> </property> <property name="interceptorNames"> <list> <value>txInterceptor</value> <value>target</value> </list> </property> </bean> Note that the class of the bean definition is always the AOP framework's ProxyFactoryBean. As explained above. as new instances of stateful interceptors may need to be created if the proxy is a "prototype". Spring AOP integrates transparently with the Spring BeanFactory concept. you should check the capabilities of Acegi Security for Spring. (Of course.springframework. flexible security framework that integrates with Spring using AOP.framework.beans. a powerful. before rolling your own security infrastructure. The following XML stanza illustrates how to define an AOP proxy: <bean id="myTest" class="org.) The "interceptorNames" property of the ProxyFactoryBean takes a list of String. Transaction management is not tied to JTA. It's also possible to use Spring AOP to implement application-specific aspects.) The names in this list can beinterceptors or pointcuts (interceptors and information about when they 17 . you can use declarative nested transactions using Spring.• doing JDBC operations on Oracle. Spring transaction management can work with different transaction strategies.springframework. rather than a singleton bean definition. (Bean names must be used rather than bean references.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>org. although the type of the bean as used in references or returned by the BeanFactory getBean() method will depend on the proxy interfaces. As with any object. Code obtaining an object from a Spring BeanFactory doesn't need to know whether or not it is advised. Successful examples we've seen include: • Custom security interception. the contract will be defined by the interfaces the object implements.

mi). However. There are a number of ways to set up proxying more concisely.addInterceptor(0. and views. It is the name of a bean in the factory that implements the proxy interface. although it is not derived from Struts.getProxy(). The "target" value in the list above automatically creates an "invoker interceptor" wrapping the target object. 18 .should apply). DebugInterceptor di = new DebugInterceptor(). Spring's MVC is very flexible. Spring MVC is entirely based on interfaces. just about every part of the Spring MVC framework is configurable via plugging in your own interface. factory. It's also possible to construct AOP proxies programmatically without using a BeanFactory. Spring has successfully demonstrated the value proposition. JavaBean models. Unlike Struts. ProxyFactory factory = new ProxyFactory(target). with a single instance executing on behalf of all clients. We believe that it's generally best to externalize the wiring of applications from Java code. if you don't need the full power of the AOP framework. For example. although this is more rarely used: TestBean target = new TestBean(). Of course we also provide convenience classes as an implementation option.0 annotations to drive transactional proxying without XML metadata. MVC web framework Spring includes a powerful and highly configurable MVC web framework.addInterceptor(1. For example: • • Spring provides a very clean division between controllers. di). Furthermore. other objects can reference it via <ref> elements and these references will be set by Spring IoC. A Spring Controller is similar to a Struts Action in that it is a multithreaded service object. MyInterceptor mi = new MyInterceptor(). we believe that Spring MVC has some significant advantages over Struts. and AOP is no exception. or the ability to use a single piece of XML to apply a consistent proxying strategy to many beans defined in a Spring factory. factory. which forces your Action and Form objects into concrete inheritance(thus taking away your single shot at concrete inheritance in Java). The use of AOP as an alternative to EJB (version 2 or above) for delivering enterprise services is growing in importance. Spring's MVC model is most similar to that of Struts. The myTest bean in this example can be used like any other bean in the bean factory. such as using Java 5. // An "invoker interceptor" is automatically added to wrap the target ITestBean tb = (ITestBean) factory.

You don't get pushed to use JSP if you don't want to. Spring MVC web tiers are typically easier to test than Struts web tiers.googleKey = googleKey. safeSearch. filter. maxResults.googleKey. 19 . } public void setGoogleKey(String googleKey) { this. query. you can have as many dispatcher servlets as you need in a Spring MVC application. public void setGoogle(IGoogleSearchPort google) { this.google = google. Spring provides an integrated framework for all tiers of your application. As in Struts 1.for example. } public ModelAndView handleRequest( HttpServletRequest request.getParameter("query"). This controller performs a Google search in its handleRequest() method: public class GoogleSearchController implements Controller { private IGoogleSearchPort google. Spring Controllers are configured via IoC like any other objects. This makes them easy to test. // Use google business object google. and beautifully integrated with other objects managed by Spring. lr. HttpServletResponse response) throws ServletException. XLST or other view technologies. your own templating language .. GoogleSearchResult result = // Google property definitions omitted. IOException { String query = request.doGoogleSearch(this. restrict. private String googleKey.. The following example shows how a simple Spring Controller can access business objects defined in the same application context. oe).1 and above. Struts and other dedicated web frameworks leave you on your own in implementing your business objects. you can use Velocity.you can easily implement the Spring View interface to integrate it. making it easy to factor out behavior common to the handling of many requests. The web tier becomes a thin layer on top of a business object layer. like WebWork. If you want to use a custom view mechanism .• • • • • Spring. This encourages good practice. provides interceptors as well as controllers. start. ie. Spring MVC is truly view-agnostic. due to the avoidance of forced concreteinheritance and explicit dependence of controllers on the dispatcher servlet.

The interface could equally be implemented by a plain Java object. Spring IoC isolates this controller from the underlying web services library. as EJBs depend heavily on the container and are hard to test in isolation.html).) Spring provides convenient superclasses for session beans and message driven beans that make this very easy. Spring can provide important benefits in both EJB implementation and client-side access to EJBs.org/docs/web_mvc. A good introduction to the Spring MVC framework is Thomas Risberg's Spring MVC tutorial(http://www.springframework. "result". returned by a Spring FactoryBean. and was discussed in a recent TSS article by its architect.html).springframework.AbstractStatelessSessionBean. We have Spring users who use Spring for middle tier management and data access but use Struts. or EJB proxy. Thiscontroller contains no resource lookup. Tapestry or JSF in the web tier. mock object. by automatically loading a BeanFactory based on an XML document included in the EJB Jar file. nothing except code necessary to support its web interaction. test stub. Implementing EJBs If you choose to use EJB. IGoogleSearchPort is a GLUE web services proxy. Keith Donald.ejb. However. If you're happy with your favourite MVC framework. In the prototype this code is taken from.springframework. Spring also provides support for data binding. See also "Web MVC with the Spring Framework" (http://www.result). a powerful framework that provides a higher level of abstraction for web flows than any traditional web MVC framework. (Among other things. A forthcoming article in this series will discuss Spring MVC in detail. 20 . Spring's layered infrastructure allows you to use the rest of Spring without our MVC layer. This means that a stateless session EJB might obtain and use a collaborator like this: import org. as discussed below. If your requirements are really complex.org/docs/MVC-step-by-step/Spring-MVCstep-by-step. wizards and more complex workflow. this makes it much easier to unit test business logic. } } return new ModelAndView("googleResults". It's now widely regarded as a best practice to refactor business logic into POJOs behind EJB facades.support. you should consider Spring Web Flow. WebWork. forms. public class MyEJB extends AbstractStatelessSessionBean implements MyBusinessInterface { private MyPOJO myPOJO.

test.myPOJO = getBeanFactory(). The Spring superclasses implement EJB lifecycle methods such as setSessionContext() and ejbCreate().MyComponentLocal</local> <ejb-class>com.MyComponentEJB</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <env-entry> <env-entry-name>ejb/BeanFactoryPath</env-entry-name> <env-entry-type>java. Using EJBs Spring also makes it much easier to use. we will offer support for the use of the Spring IoC container to provide richer Dependency Injection semantics in that environment. the implementing class . but their usual implementations have significant disadvantages.and any configuration it requires. Each EJB can specify its own XML document. as follows: <session> <ejb-name>myComponent</ejb-name> <local-home>com.xml</env-entryvalue></env-entry> </env-entry> </session> The myComponent-ejb-beans. These are better than spraying JNDI lookups throughout client code. } public void myBusinessMethod() { this.lang.mycom.xml deployment descriptor.String</env-entry-type> <env-entry-value>/myComponent-ejb-beans. When EJB 3.ejb.xml file will be loaded from the classpath: in this case. Many EJB applications use the Service Locatorand Business Delegate patterns. leaving the application developer to optionally implement the Spring onEjbCreate() method.myPOJO.getBean("myPOJO").mycom. such as primitiveproperties and further collaborators . We tell Spring where to load the XML document via an environment variable definition named ejb/BeanFactoryPath in the standard ejb-jar.invokeMethod().myEjbBeanLocalHome</local-home> <local>com. We will also integrate the JSR-220 O/R mapping API with Spring as a supported data access API. in the root of the EJB Jar file. so this mechanism can be used multiple times per EJB Jar file. } } Assuming that MyPOJO is an interface.is hidden in the XML bean factory definition.protected void onEjbCreate() { this. as well as implement EJBs. For example: 21 .0 is available in public draft.

• •

Typically code using EJBs depends on Service Locator or Business Delegate singletons, making it hard to test. In the case of the Service Locator pattern used without a Business Delegate, application code still ends up having to invoke the create() method on an EJB home, and deal with the resulting exceptions. Thus it remains tied to the EJB API and the complexity of the EJB programming model. Implementing the Business Delegate pattern typically results in significant code duplication, where we have to write numerous methods that simply call the same method on the EJB.

For these and other reasons, traditional EJB access, as demonstrated in applications such as the Sun Adventure Builder and OTN J2EE Virtual Shopping Mall, can reduce productivity and result in significant complexity. Spring steps beyond this by introducing codeless business delegates. With Spring you'll never need to write another Service Locator, another JNDI lookup, or duplicate methods in a hand-coded Business Delegate unless you're adding real value. For example, imagine that we have a web controller that uses a local EJB. We'll follow best practice and use the EJBBusiness Methods Interface pattern, so that the EJB's local interface extends a non EJB-specific business methodsinterface. (One of the main reasons to do this is to ensure that synchronization between method signatures in local interface and bean implementation class is automatic.) Let's call this business methods interface MyComponent. Of course we'll also need to implement the local home interface and provide a bean implementation class that implements SessionBean and the MyComponent business methods interface. With Spring EJB access, the only Java coding we'll need to do to hook up our web tier controller to the EJB implementation is to expose a setter method of type MyComponent on our controller. This will save the reference as an instance variable like this: private MyComponent myComponent; public void setMyComponent(MyComponent myComponent) { this.myComponent = myComponent; } We can subsequently use this instance variable in any business method. Spring does the rest of the work automatically, via XML bean definition entries like this. LocalStatelessSessionProxyFactoryBean is a generic factory bean that can be used for any EJB. The object it creates can be cast by Spring to the MyComponent type automatically. <bean id="myComponent" class="org.springframework.ejb.access.LocalStatelessSessionProxyFactory Bean"> <property name="jndiName" value="myComponent" /> <property name="businessInterface" value="com.mycom.MyComponent"

22

/> </bean> <bean id="myController" class = "com.mycom.myController" > <property name="myComponent" ref="myComponent" /> </bean> There's a lot of magic happening behind the scenes, courtesy of the Spring AOP framework, although you aren't forced to work with AOP concepts to enjoy the results. The "myComponent" bean definition creates a proxy for the EJB, which implements the business method interface. The EJB local home is cached on startup, so there's normally only a single JNDI lookup. (There is also support for retry on failure, so an EJB redeployment won't cause the client to fail.) Eachtime the EJB is invoked, the proxy invokes the create() method on the local EJB and invokes the corresponding business method on the EJB. The myController bean definition sets the myController property of the controller class to this proxy. This EJB access mechanism delivers huge simplification of application code: • The web tier code has no dependence on the use of EJB. If we want to replace this EJB reference with a POJO or a mock object or other test stub, we could simply change the myComponent bean definition without changing a line of Java code We haven't had to write a single line of JNDI lookup or other EJB plumbing code as part of our application.

We can also apply the same approach to remote EJBs, via the similar org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean factory bean. However, it's trickier to conceal the RemoteExceptions on the business methods interface of a remote EJB. (Spring does let you do this, if you wish to provide a client-side service interface that matches the EJB remote interface but without the "throws RemoteException" clause in the method signatures.)

Testing
As you've probably gathered, I and the other Spring developers are firm believers in the importance of comprehensiveunit testing. We believe that it's essential that frameworks are thoroughly unit tested, and that a prime goal of framework design should be to make applications built on the framework easy to unit test. Spring itself has an excellent unit test suite. We've found the benefits of test first development to be very real on this project. For example, it has made working as an internationally distributed team extremely efficient, and users comment that CVS snapshots tend to be stable and safe to use. We believe that applications built on Spring are very easy to test, for the following reasons:

23

• • •

IoC facilitates unit testing Applications don't contain plumbing code directly using J2EE services such as JNDI, which is typically hard to test Spring bean factories or contexts can be set up outside a container

The ability to set up a Spring bean factory outside a container offers interesting options for the development process. In several web application projects using Spring, work has started by defining the business interfaces and integrationtesting their implementation outside a web container. Only after business functionality is substantially complete is a thin layer added to provide a web interface. Since Spring 1.1.1, Spring has provided powerful and unique support for a form of integration testing outside the deployed environment. This is not intended as a substitute for unit testing or testing against the deployed environment. However, it can significantly improve productivity. The org.springframework.test package provides valuable superclasses for integration tests using a Spring container, but not dependent on an application server or other deployed environment. Such tests can run in JUnit--even in an IDE-without any special deployment step. They will be slower to run than unit tests, but much faster to run than Cactus tests or remote tests relying on deployment to an application server. Typically it is possible to run hundreds of tests hitting a development database--usually not an embedded database, but the product used in production--within seconds, rather than minutes or hours. Such tests can quickly verify correct wiring of your Spring contexts, and data access using JDBC or ORM tool, such as correctness of SQL statements. For example, you can test your DAO implementation classes. The enabling functionality in the org.springframework.test package includes: • • • The ability to populate JUnit test cases via Dependency Injection. This makes it possible to reuse Spring XML configuration when testing, and eliminates the need for custom setup code for tests. The ability to cache container configuration between test cases, which greatly increases performance where slow-to-initialize resources such as JDBC connection pools or Hibernate SessionFactories are concerned. Infrastructure to create a transaction around each test method and roll it back at the conclusion of the test by default. This makes it possible for tests to perform any kind of data access without worrying about the effect on the environments of other tests. In my experience across several complex projects using this functionality, the productivity and speed gain of such a rollback-based approach is very significant.

Who's using Spring?
There are many production applications using Spring. Users include investment and retail banking organizations, well-known dotcoms, global consultancies, academic institutions, government departments, defence contractors, several airlines, and scientific research organizations (including CERN).

24

We believe in a philosophy of "release early. the Quartz scheduler and AspectJ Integration with JSF as a web layer technology We intend to continue with rapid innovation and enhancement.3).3) Support for dynamic reconfiguration of running applications Support for the writing of application objects in languages other than Java.0 final release (March 2004) through version 1. eliminating the need for XML metadata to identify transactional methods Support for JMX management of Spring-managed objects (1. a number of users begin by using our JDBC or other data access functionality. Integration of Spring Web Flow into the Spring core (planned for release 1. Jython or otherscripting languages running on the Java platform. which extends the reach of the Spring platform to areas that are not necessarily integral to 25 . So we don't develop features that no one has a use for. 2005). Planned enhancements include: • XML configuration enhancements (planned for release 1.0 annotations (1. For example. Roadmap Since the first version of this article. release often. and we listen carefully to our user community. validated tag. Integration with Jasper Reports. Such objects will benefit from the full services of the Spring IoC container and will allow dynamic reloading when the script changes.2 release Support for declarative transaction management configured by Java 5. in October 2003. Since that time enhancements include: • • • • • • • The introduction of a remoting framework supporting multiple protocols including RMI and various web services protocols Support for Method Injection and other IoC container enhancements such as the ability to manage objects obtained from calls to static or instance factory methods Integration with more data access technologies. but will be ideal for developers of third-party products that are based on Spring.2 final (May 2005).2). including TopLink and Hibernate 3 as well as Hibernate 2 in the recent 1." so maintenance releases and minor enhancements are typically released every 4-6 weeks. but some use components in isolation. led by Rob Harrop of Interface21. The next major release will be 1.Many users use all parts of Spring. Spring is primarily driven by user requirements. Spring has progressed through its 1. This not only has the potential to simplify typical configurations significantly and reduce configuration errors. • • • As an agile project. without affecting objects that were given references to them by the IoC container.3 (final release expected Q3. which will allow custom XML tags to extend the basic Spring configuration format by defining one or more objects in a single. such as Groovy.l (September 2004) to 1.2). Spring Modules is an associated project.

while still valuable to many users. Interestingly. 26 . so some of this functionality will probably eventually migrate into the Spring core.the Spring core. Spring provides a consistent way of managing business objects and encourages good practices such as programming to interfaces. beyond classic J2EE.0 final. JDO and other O/R mapping solutions. AOPbased caching solution. Summary Spring is a powerful framework that solves many common problems in J2EE. a declarative. This project also serves as an incubator. such as JTA or JDBC. although the first version of this article was published six months before the release of Spring 1. and integration with the Commons Validator framework. The architectural basis of Spring is an Inversion of Control container based around the use of JavaBean properties. almost all the code and configuration examples would still work unchanged in today's 1. Spring provides an AOP framework written in standard Java. Spring also provides a powerful and flexible MVC web framework that is integrated into the overall IoC container. Spring's data access architecture also integrates with TopLink. Hibernate. Spring Modules presently includes areas such as integration with the Lucene search engine and OSWorkflow workflow engine. which enables a consistent programming model over a variety of underlying transaction technologies. and also indicates the seriousness with which we take our responsibility to the community to provide a stable framework to run vital applications. which provides declarative transaction management and other enterprise services to be applied to POJOs or .2 release.if you wish . while enjoying key services traditionally associated with EJB. This demonstrates the ability of Dependency Injection and AOP to deliver a non-invasive API. Spring provides a unique data access abstraction. We are proud of our excellent record on backward compatibility. Spring also provides a unique transaction management abstraction. this is only part of the overall picture: Spring is unique in that it uses its IoCcontainer as the basic building block in a comprehensive solution that addresses all architectural tiers. Many Spring features are also usable in a wide range of Java environments.the ability to implement your own custom aspects. rather than classes. However. This framework is powerful enough to enable many applications to dispense with the complexity of EJB. including a simple and productive JDBC framework that greatlyimproves productivity and reduces the likelihood of errors.

This helps the programmer to inject the dependency such as business service at runtime. Let's see in detail: Pluggable View technology There are many view technologies such as JSP. Velocity etc. View: View is the presentation part of the application such as data entry form. The features of Spring MVC framework are the Pluggable View technology and Injection of services into controllers. Controller: The controller component delegates between Model and view. View and Controller. The Spring MVC takes the advantage of Spring framework and provides once to best and productive framework for development of web applications. What is MVC architecture? The MVC or Model View Controller architecture is famous design pattern used in designing the applications.Web Tier by Christy In this example we will give you quick overview of Spring MVC Framework. The Spring MVC is a web development framework based on the MVC (Model View Controller) design pattern. This saves lot of code duplication and coding effort. Model: Model is the business data or simple the data of the application. The Spring framework allows the developers to mix and match multiple frameworks while developing and deploying the applications. Spring framework allows us to use these view technologies. This design pattern separates the application into three parts called Model. The Spring MVC framework is the MVC stack for the development of web applications based Model View Controller (MVC) architecture. Tiles.Spring MVC Introduction • Read Introduction to Spring MVC Web Framework . Injection of services into controllers The IoC container provides the important functionality of the dependency injection. Spring's MVC components: Model: 27 . reports etc. Spring MVC The Spring Framework is light-weight container and it supports multiple frameworks and libraries.

UrlFilenameViewController 11. CancellableFormController. AbstractController 12. AbstractController 3. AbstractCommandController 6. Here is the list of key classes of Spring MVC. Velocity and Jasper templates. It wraps the business data into org.web. • DispatcherServlet The DispatcherServlet is configured in the web. How Spring MVC Works? • Read Introduction to Spring MVC Web Framework .ModelMap is used by the spring framework to hold the data.springframework. In Spring MVC Logical view and Model are represented in the object of the classorg.xml file and required URL 28 . Controller: The controller is responsible for handling all the requests from the user and then process the user request. SimpleFormController 2.ui.The class org. and it allows the developers to create views using jsp.ui.servlet.springframework. View: Framework provides pluggable view. This modules is also very extensible. Here are the list of controllers available in the Spring 2.5 framework: 1. ServletWrappingController 10. The Spring MVC modules comes with the Spring Framework distribution.ModelMap class and then pass it to the view. AbstractCommandController 4. AbstractCommandController 13. The Spring MVC modules of the Spring Framework well integrates with rest of the framework.Web Tier by Christy In this we will see the request flow for the spring framework. SimpleFormController 14. We will also show you the request flow diagram illustrating the working of Spring MVC module. CancellableFormController 5. ServletForwardingController 9. Spring MVC is based on the MVC design pattern.springframework. In the next sections we will see the examples of all these controllers. MultiActionController 7. ParameterizableViewController 8.ModelAndView.

6. Then the DispatcherServlet passes the model object to the View. Finally ServletContainer sends the result back to the user. Client access some URL on the server. Simplified Spring MVC architecture diagram Following diagram shows the simplified architecture of Spring MVC: Let's understand the sequences of the events happens when a request is received by the Spring MVC. and an onSubmit chain for convenient overriding. It provides the configurable form and success views. SimpleFormController The SimpleFormController is the Concrete FormController implementation. 5. 4. Then the Controller executes the logic business logic (if written by the programmer) and then returns ModeAndView object to the DispatcherServlet. In this process framework reads the configuration information from 29 . Request handling steps in Spring MVC 1. Automatically resubmits to the form view in case of validation errors. 3. 3. It works as the front controller and handle all the request from the user. • • ModelAndView This class works as the holder for both Model and View in the Spring MVC. 2. The DispatcherServlet configured in web. Following events happens when DispatcherServlet receives are request: 1. After receiving the request it finds the appropriate Handler Mappings. Request flow in Spring MVC Spring MVC is request driven and DispatcherServlet handles the request from client and then dispatches the request to controllers. The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.xml file receives the request. It tightly integrates with the Spring IoC container and allows the developers to use every features of Spring framework. The following diagram illustrates the request flow in Spring MVC.patterns are mapped to this Servlet. The DispatcherServlet determines the view from the ModelAndView object. 2. and renders the success view in case of a valid submission. The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. The Spring Front Controller (DispatcherServlet) intercepts the Request. The Handle Mappings maps the client request to appropriate Controller.

< Then DispatcherServlet dispatch the request to the appropriate Controller. Developers extends the abstract controller provided by the framework and writes the business logic there. 6. Based on the values in the ModelAndView Controller resolves the actual view. 5. Spring MVC module is based on the MVC design pattern. In Spring MVC DispatcherServlet plays very important role. The actual business related processing is done in the Controller.the configuration file or from the annotated controller list. The main components involved are DispatcherServlet. Then the selected view is rendered and output is generated in the form of HttpServletResponse. The Spring MVC module provides a lot offlexibility to easily develop MVC based web applications. Then the Controller processes the Client Request. Jasper or any other configured view resolver. Controller and Views. It handles the user request and delegates it with Controller. Velocity. which sends the output to the user. it executes the logic defined in the Controller method and finally returns the ModelAndView object back to the Front Controller. which can be JSP. 30 . DispatcherServlet works as the controller and it delegates the request to the Controller. It provides many controllers that can be used to achieve different jobs. 4. Finally Controller sends the response to the Servlet container. FreeMaker. The Handler Adapters involves in this process. In the next section we will see the controller stack in Spring MVC Controllers in Spring MVC • Read Introduction to Spring MVC Web Framework . Following diagram shows the very simplified architecture: In this Spring MVC.Web Tier by Christy In this we will will understand the controllers hierarchy in Spring MVC Module.

ServletForwardingController 9. AbstractCommandController 4. which is designed for specific tasks. ServletWrappingController 10. MultiActionController 7. AbstractController 12. AbstractCommandController 13. AbstractController 3. UrlFilenameViewController 11.Spring MVC provides many abstract controllers. SimpleFormController 2. SimpleFormController 14. Following diagram shows the Controllers hierarchy in Spring MVC: 31 . CancellableFormController 5. ParameterizableViewController 8. Here is the list of anstractcontrollers that comes with the Spring MVC module: 1. AbstractCommandController 6. CancellableFormController.

Starting the development using Spring MVC Framework • Read Introduction to Spring MVC Web Framework . We will also provide you the examples codes illustrating the usage of these controllers.Web Tier by Christy 32 .In the next sections we will be learning about all these controllers.

2. Understanding the example: We are going to develop a very simple example that will just print "Hello World" message on the browser. We will have to follow the following steps: 1. Also download Spring 2. 9.eclipse. Introduction to the Spring Framework • Read Introduction to Spring MVC Web Framework . 8.xml file.Web Tier by Christy Spring is grate framework for development of Enterprise grade applications. Spring can be used to configure declarative transaction management. 2. Add necessary configuration in web.5. Create dispatcher-servlet.5 or above Getting stated: Please make sure that JDK is installed on your computer. In the next section we will create new project in eclipse and add spring libraries.3 or above download it from the official website at http://www. And check application in browser. 4.xml and add required mapping the xml file. Create Controller class. JDK 1.5 or above Eclipse IDE 3. 7. We will also see what all configuration and code is to be developed. 3.In this we will quickly start developing the application using Spring MVC module. Add Spring libraries to the project. mailing facilities and various options in 33 . Create new dynamic web application in eclipse. We will use Eclipse IDE to develop run and test the application. 3. 1. if it is not 3.3 or above Tomcat 6 or later Spring framework 2. Finally run tomcat and deploy the application on the tomcat. 5. 6. We will first develop a simple Spring MVC Hello World example and then test on the Tomcat server. Create JSP file to display "Hello World" message. Setup tomcat as container to run the application. remote access to your logic using RMI or web services.org/downloads/. Spring is a light-weight framework for the development of enterprise-ready applications. run the example program. 4. Check your Eclipse IDE version. What is required? In order to complete the tutorial you will need the following software and libraries. We we will also see how to compile.

and making it easy to demarcate transactions without dealing with low-level issues. Modules in the Spring framework are: 1. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. built on core Spring functionality. This allowing the developer to add the pluggable transaction managers. Velocity.. AOP is used in Spring: • To provide declarative enterprise services. it allows to use in parts and leave the other components which is not required by the application. Tiles. • • • • Spring Architecture Spring is well-organized architecture consisting of seven modules. which includes Spring MVC. especially as a replacement for EJB declarative services. and accommodates multiple view technologies like JSP. which simplifies the error handling strategy Integration with Hibernate. complementing their use of OOP with AOP Spring ORM The ORM package is related to the database access. including JDO. The most important such service is declarative transaction management. < JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exceptionhierarchy. It provides integration layers for popular object-relational mapping APIs. Hibernate and iBatis. This framework is highly configurable via strategy interfaces. JDO and iBATIS. and iBATIS: Spring provides best Integration services with Hibernate. and POI. One of the key components of Spring is the AOP framework. which builds on Spring's transaction abstraction. JDO. But other frameworks can be easily used instead of Spring MVC Framework. Features of Spring Framework: • Transaction Management: Spring framework provides a generic abstraction layer for transaction management. Spring AOP 2. AOP Framework: Spring is best AOP framework MVC Framework: Spring comes with MVC web application framework. iText. • To allow users to implement custom aspects. 3. Spring framework can be used in modular fashion. 34 . Spring Web The Spring Web module is part of Spring’s web application development stack.persisting your data to a database.

Spring DAO The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC. 7. The following diagram represents the Spring Framework Architecture 35 . 5. and the ability for application objects to obtain resources using a consistent API. creation and access of the objects from your actual program logic. The BeanFactory provides a factory pattern which separates the dependencies like initialization. Spring Web MVC This is the Module which provides the MVC implementations for the web applications. Hibernate or JDO. Spring Context This package builds on the beans package to add support for message sources and for the Observer design pattern. 6. Spring Core The Core package is the most import component of the Spring Framework. This component provides the Dependency Injection features.4.

Once extract go to the extracted folder and you will find many files.1-with-dependencies.bat 36 .zip) into your favorite directory.Web Tier by Christy Spring Framework Install . In the last section we downloaded the latest version of Spring framework (spring-framework-2.zip).5. Extracting Spring download Now extract the downloaded file (spring-framework-2. Depending upon the system speed it will take around 1 minute. Here are some of the file names: • build.a quick tutorial to install Spring Framework on your development environment.1-with-dependencies.5. In this section we will extract the downloaded file and pick the required libraries and then install in our development environment.Spring Framework Architecture Installing Spring Framework • Read Introduction to Spring MVC Web Framework .

xml changelog. These jar files are: • • • • spring-aop.jar 37 .xml notice.txt project. We are mostly concern with these jar files. We will copy these jar files into our development environment.jar spring-context.txt maven.• • • • • • • • • build.txt license.bat Here is the screen shot of the directory: The dist directory of the spring framework contains the spring modules (modules directory) library files.txt tests.properties readme.jar spring-context-support.jar spring-beans.xml build-continuous.

Apache Axis 1.6.7.org/axis) .jar .Ant 1.required at runtime when using Spring's AspectJ support NOTE: aspectjtools.apache.0b4.7.org) . which contains required library files for the application.jar spring-webmvc-struts. Another most important directory is "lib". (aspectj/aspectjtools.jar .0 beta 4 (http://www.jar) . axis/wsdl4j.6 (http://www.jar.antlr.AspectJ 1.required for building the framework .jar .beanshell.4 (http://ws.jar. * ant/ant.jar spring-webmvc.jar.4 (http://www.ANTLR 2.jar spring-test.jar spring-orm.sourceforge.required for building the framework . Note that each of these libraries is subject to the respective license. It needs to be taken from the AspectJ distribution or from Spring CVS. ant-trax.5. ant/ant-launcher.jar spring-web.jar spring-tx.org) .7 (http://ant.BeanShell 2.0 (http://aopalliance.jar .jar is not included in the Spring distribution because of its size.org) .apache. ant-junit.jar * aspectj/aspectjweaver. check the respective project distribution/website before using any of them in your own applications.required for building the framework .jar We will be using these libraries as per our requirement in our application. aspectj/aspectjrt.jar spring-jdbc.jar spring-webmvc-portlet.jar.jar.• • • • • • • • • • spring-core.aspectj.required for running JPetStore * bsh/bsh-2.AOP Alliance 1.org) .jar and spring-aop.jar .included in spring.net) . Note that this is only necessary if you want to rebuild the Spring jars including the AspectJ aspects.used to build the framework and the sample apps * antlr/antlr-2. The following libraries are included in the Spring Framework distribution because they are required either for building the framework or for running the sample apps.jar. * axis/axis.required for running PetClinic (by Hibernate) * aopalliance/aopalliance.jar spring-jms.required for building the framework 38 .

emory.1-beta-7.6.required at runtime when using Spring's Hessian/Burlap remoting support * cglib/cglib-nodep-2.caucho.3 version) (http://www.required at runtime when using Spring's BeanShell support * bnd/bnd.0.1_3.5.3 (http://www.jar .BND tool 0.required for building the framework .jar .org) .3.3.org) .11 (http://www.2 connection pool (http://sourceforge.edu/util/backport-util-concurrent) .0 (http://ehcache.1 (http://dev2dev.EHCache 1.required for building the framework .208 (http://www.required at runtime when using Spring's backport-concurrent support * dom4j/dom4j-1. version 3.required for building the framework .required at runtime when using Spring's EHCache support .jar .com/hessian) .jar .1.dom4j.jar .required at runtime when proxying full target classes via Spring AOP * commonj/commonj-twm.1 XML parser (http://www. easymock/easymockclassextension.CGLIB 2. dom4j/jaxen-1.aqute.0 (http://dcl.bea.jar .jar .required for building the framework .Hessian/Burlap 3.net) .sourceforge.1.required for building the framework .required at runtime when using Spring's CommonJ support * concurrent/backport-util-concurrent.3.required at runtime when using Spring's C3P0NativeJdbcExtractor .required for adding OSGi entries to the jar manifests at build time * c3p0/c3p0-0.2 (JDK 1.FreeMarker 2.3.required for running PetClinic (by Hibernate) * easymock/easymock.Dawid Kurzyniec's JSR-166 backport.jar .0.net/projects/c3p0) .required at runtime when using Spring's FreeMarker support 39 .sourceforge.html) .CommonJ TimerManager and WorkManager API 1.required for building and running the framework's test suite * ehcache/ehcache-1.2.mathcs.jar .9.biz/Code/Bnd) .net) .1.1.required for running PetClinic (by Hibernate) * freemarker/freemarker.com/wlplatform/commonj/twm.EasyMock 1.jar .9.required for building the framework .3 (http://cglib.1_3 with ObjectWeb ASM 1.required for running Image Database * caucho/hessian-3.freemarker.jar.easymock..1.C3P0 0.6.required for building the framework .org) .DOM4J 1.

0 b677 (http://ibatis.com/products/javabeans/glasgow/jaf.apache.jar .jar .HSQLDB 1.1.hibernate.required at runtime when using Spring's Hibernate-specific JPA support * hibernate/jboss-archive-browsing.Hibernate 3.net) .net) .dev.0.jar .JBoss Archive Browsing 5.JavaBeans Activation Framework 1.required at runtime when using Spring's Hibernate Annotations support * hibernate/hibernate-entitymanager.Groovy 1.sourceforge.required at runtime when using Hibernate EntityManager * hsqldb/hsqldb.lowagie.1 (http://hsqldb.com/itext) .java.iText PDF 2.sun.jar .x support * itext/iText-2.7.677.0.required at runtime when using Spring's Hibernate support * hibernate/hibernate-annotation.jar .required for building the framework .hibernate.3.jar .0.required at runtime when using Spring's iBATIS SQL Maps 2.5.required at runtime when using Spring's Groovy support * hibernate/hibernate3.required at runtime when using Spring's AbstractPdfView * j2ee/activation.1 (http://groovy.required for running JPetStore and PetClinic * ibatis/ibatis-2.3.3.0 alpha .jar .required at runtime when using Spring's Common Annotations support on JDK < 1.jar 40 .5 (http://www.1 (http://java.Hibernate EntityManager 3.jar .1 (http://www.7 (http://www.org) .hibernate.required for building the framework .0.5.iBATIS SQL Maps 2.required for building the framework .required for building the "tiger" part of the framework .6 * j2ee/common-annotations.org/en/jsr/detail?id=250) .required for building the framework * groovy/groovy-1.JSR-250 Common Annotations (http://jcp.Hibernate Annotations 3.6 * j2ee/connector.required at runtime when using Spring's JavaMailSender on JDK < 1.jar .jar .jar .0 (http://www.* glassfish/glassfish-clapi.8.3.org) .required for building the "tiger" part of the framework .2.required for building the framework .org) .html) .codehaus.org) .org) .GlassFish ClassLoader API extract (http://glassfish.0.

sun.sun.jar .jar .required at runtime when using Spring's JSP support * j2ee/jstl.0 (http://java.required for building the framework .sun.Java Persistence API 1.5 (http://java.required at runtime when using Spring's JSF support * j2ee/jsp-api.required for building the framework .required for building the framework .required for building the framework .sun.JavaMail 1.1 (http://java.com/xml/jaxrpc) .jar .Java Transaction API 1.JSP Standard Tag Library API 1.JAX-RPC API 1.required at runtime when using Spring's JavaMailSender * j2ee/persistence.jar .jar .1 (java.required for building the framework .jar .sun.jar .required at runtime when using Spring's EJB support * j2ee/el-api.required at runtime when using Spring's JtaTransactionManager * j2ee/mail.1 (http://java.1's EL API (http://java.jar .required for building the framework .com/products/jms) .JSF API 1.com/products/jstl) .Enterprise JavaBeans API 3.oracle.com/products/jsp) .required for building the framework .required at runtime when using Spring's JMS support * j2ee/jsf-api.com/j2ee/javaserverfaces) .0 (http://java.J2EE Connector Architecture 1.. as used by JSF 1.com/products/jsp).com/technology/products/ias/toplink/jpa) .sun.1 (http://java.required at runtime when using Spring's JstlView * j2ee/jta.required at runtime when using Spring's JSF 1.JSP 2.required for building the framework .sun.required at runtime when using Spring's JPA support 41 .4 (http://java.jar .2 .com/products/jta) .2 support * j2ee/jaxrpc.com/products/ejb) .1 (http://java.Java Message Service API 1.com/j2ee/connector) .sun.required at runtime when using Spring's JAX-RPC support * j2ee/jms.jar .JSP API 2.0 (http://www.required for building the framework .required for building the framework .com/products/javamail) .required for building the framework * j2ee/ejb-api.sun.sun.

apache.apache.required for building the framework .required for running JPetStore * jakarta-commons/commons-digester.org/commons/attributes) .org/commons/collections) .jar .2 (http://jakarta.Commons Collections 3.com/products/jdbc) .Servlet API 2.required at runtime when using Spring's CommonsHttpInvokerRequestExecutor * jakarta-commons/commons-io.sun.apache.required at runtime when using Spring's web support * jakarta-commons/commons-attributes-api.apache.jar .jar .org/commons/discovery) .Commons FileUpload 1.org/commons/io) 42 .apache.required for building the framework .jar .required for running JPetStore (by Axis) * jakarta-commons/commons-fileupload.apache.2 (http://jakarta.JDBC RowSet Implementations 1.jar .jar .required at runtime when using Spring's RowSet support on JDK < 1.jar .apache.org/commons/digester) .com/products/servlet) .jar .2 (http://jakarta.2.2 (http://jakarta.2 (http://jakarta.7 (http://jakarta.jar .required for running PetClinic.1 (http://hc.required for building the framework .1 (http://jakarta.jar has a patched manifest (not declaring QDox and Ant as required extensions) .required for building the framework .commons-attributes-api.org/commons/dbcp) .jar .org/httpclient-3.sun.org/commons/fileupload) .required for building the framework . Hibernate) * jakarta-commons/commons-dbcp.Commons Digester 1.Commons DBCP 1.Commons Attributes 2.4 (http://java.Commons Discovery 0.Commons BeanUtils 1.required for running JPetStore's Struts web tier * jakarta-commons/commons-collections.apache.required at runtime when using Spring's CommonsDbcpNativeJdbcExtractor .required for running JPetStore's Struts web tier * jakarta-commons/commons-discovery.apache.Commons IO 1.required at runtime when using Spring's CommonsMultipartResolver * jakarta-commons/commons-httpclient.0.x) .1 (http://java.org/commons/beanutils) .6 (http://jakarta.3. JPetStore (by Commons DBCP.Commons HttpClient 3. jakarta-commons/commonsattributes-compiler.jar .jar.5 * j2ee/servlet-api.required at runtime when using Spring's Commons Attributes support * jakarta-commons/commons-beanutils.required for building the framework .* j2ee/rowset.

jar .required at runtime when using Spring's OpenJPA support (by OpenJPA) * jakarta-commons/commons-logging.4. as Spring uses it for all logging * jakarta-commons/commons-pool.jar .jar.required at runtime when using Spring's JasperReports support * jaxws/jws-api.apache.2 (http://jakarta.org/jdo) .0) * jexcelapi/jxl.org/commons/logging) .jar .apache. jaxws/saaj-api.sourceforge.JExcelApi 2.required for running JPetStore's Struts web tier on servers that eagerly load tag libraries (e.jar for JDO 1.jar .JAX-WS 2..com/p/jarjar) .jamonapi.6 * jdo/jdo2-api.g.required at runtime when using Spring's AbstractJExcelView 43 . Resin) * jakarta-taglibs/standard.com) .Commons Logging 1.net) .required for building the framework jars * jasperreports/jasperreports-2.required for building the framework .required for building the framework .2 (http://jasperreports.required for building the framework .required at runtime when running Spring's JAX-WS support tests on JDK < 1.0 RC5 (http://code.apache.java.net) .2.org/commons/pool) .Commons Pool 1.apache.jar.required at runtime when using Spring's CommonsMultipartResolver (by Commons FileUpload) * jakarta-commons/commons-lang.2 (http://jakarta.Jakarta's JSTL implementation 1.org/commons/lang) .2 API (https://jax-ws.jar .1. Countries * jamon/jamon-2.3 (http://jakarta.required at runtime.required for building the framework .6 (http://jexcelapi.4 (http://www.sourceforge.JDO API 2.0.required for running JPetStore.0 (http://db. jaxws/jaxws-api.jar .google. PetClinic.apache. jaxws/jaxb-api.jar.required for running JPetStore and Image Database (by Commons DBCP) * jakarta-commons/commons-validator.jar .Jar Jar Links 1.jar .1.required at runtime when using Spring's JDO support (or jdo.Commons Lang 2.4 (http://jakarta.dev.Commons Validator 1.jar .0.required for building the framework .1.net) .6.JAMon API (Java Application Monitor) 2.JasperReports 2.1 (http://jakarta.org/commons/validator) .org/taglibs) .apache.jar .required at runtime when using Spring's JamonPerformanceMonitorInterceptor * jarjar/jarjar.jar .

jar .jar .apache.JRuby 1.JUnit 3.0.8.Apache POI 3.JMX 1.experlog.required at runtime when using Spring's JMX support on JDK < 1.0.2.jar .0.Log4J 1. junit/junit-4.com/technology/tech/java/oc4j) .codehaus.1.0.required for building the framework .1 ClassLoader API extract (http://www.5) * jotm/jotm.org) .jar .0 (http://xapool. also included in JOTM) .jar .2.OpenJPA 1.1 reference implementation .0.1 reference implementation) .* jmx/jmxri.jar .required at runtime when using Spring's AbstractExcelView * portlet/portlet-api.1 (http://openjpa.4.5.jar .org) .required for building the framework .org/poi) .required for building the framework .required for building the framework .JOTM 2.1 reference implementation .jar .4 (http://www.jar .jar .Portlet API 1.required at runtime when using Spring's JRuby support * junit/junit-3.JMXMP connector (from JMX Remote API 1.required at runtime when using Spring's JPA support with OpenJPA as provider * poi/poi-3.Oracle OC4J 10.0.3.required at runtime when using Spring's JMX support on JDK < 1.required for building the framework .required at runtime when using Spring's XAPoolNativeJdbcExtractor * jruby/jruby.oracle.required for building and running the framework's test suite * log4j/log4j-1.jar .XAPool 1.1 (http://jakarta.0.5 * jmx/jmxremote.apache.required at runtime when using Spring's Log4jConfigurer * oc4j/oc4j-clapi.required at runtime when using Spring's JotmFactoryBean * jotm/xapool.1.2 / 4.1.14.1 (http://jruby.required at runtime when using the JMXMP connector (even on JDK 1.10 (http://jotm.8.required for building the framework .JMX Remote API 1.0.jar.2.org/log4j) .0 (http://jcp.14 (http://logging.required for building the framework * openjpa/openjpa-1.5 * jmx/jmxremote_optional.apache.2.objectweb.org) .junit.com.org) .org/aboutJava/communityprocess/final/jsr168) 44 .jar .

1.jar .5 (http://qdox.Oracle TopLink 10.used by Commons Attributes 2.2.QDox 1.x support or Tiles 1.0.required for building the framework .1.required at runtime when using Spring's VelocityView 45 .jar .Serp 1.jar.required at runtime when using Spring's JPA support with TopLink as provider * velocity/velocity-1.required at runtime when using the Tiles2 TilesView * tomcat/catalina. tiles/tiles-jsp-2.5.0.required for building the framework .required for building the framework .jar .required for building the framework .oracle.jar at runtime when using Spring's TopLink support * toplink/toplink-essentials.1 (http://serp.5-jdk15.0.required at runtime when using OpenJPA * struts/struts.6.9 (http://jakarta.Apache Tiles 2.apache.oracle.5 (http://jakarta.13.replaced with full toplink.required for building the framework and the attributes version of JPetStore * quartz/quartz-all-1.0 (http://www.jar.opensymphony. tiles/tiles-core-2.org) . tomcat/naming-resources.required at runtime when using Spring's Quartz scheduling support * serp/serp-1.Apache Tomcat 5.6.jar .net) .org) .com/quartz) .jar .org/struts) .5.required at runtime when using the Struts 1.sourceforge.com/technology/products/ias/toplink/jpa) .5 (http://tiles.5.jar.apache.jar .Velocity 1.required for building the framework .org) .com/technology/products/ias/toplink) .Quartz 1.apache.TestNG 5.3 API (http://www.apache.5.required for building and running the framework's test suite * tiles/tiles-api-2.23 (http://tomcat.5 (http://testng.x TilesView .jar .required for building the framework .codehaus.5..0.org/velocity) .0.required for building the Tomcat-specific weaver * toplink/toplink-api.Apache Struts 1.jar .13.required for running JPetStore's Struts web tier * testng/testng-5.Oracle TopLink Essentials v2 b41 (http://www.5.required for building the framework .jar .2 to parse source-level metadata in the build process .jar .required at runtime when using Spring's Portlet support * qdox/qdox-1.org) .

* velocity/velocity-tools-view-1.org/schema/beans" xmlns:xsi="http://www.Velocity Tools 1.xsd"> <bean id="mybean" class="Inject" p:name="Girish" p:age="24" p:address="Noida" p:company="javabeat.Here "Inject" is the name of the bean class which would be referred in thexml file with the id "mybean". Spring Injection Example • Read Introduction to Spring MVC Web Framework . <bean id="mybean" class="Inject">:.net" 46 .apache.springframework.0" encoding="UTF-8"?> <beans xmlns="http://www. xmlns:p="http://www.org/schema/p":-Here we have introduced namespace:"p" that cannot be validated.org/schema/beans/springbeans.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.org/velocity/tools) .springframework.required for building the framework .w3.springframework.required at runtime when using VelocityView's support for Velocity Tools You can use above libraries in your application as per your requirement.jar .xml <?xml version="1. p:name="Girish" :-Here we simply use the property name in the "p" namespace. Extension namespaces also allows us to supply property values by using attributes . In the next section I will show you how to setup development environment step-bystep. The given example below gives the brief description of the extension name spaces that can be used in the spring framework With the use of extensible name space you can make Spring configuration file more simpler to use for many tasks which can occurs repeatedly . as in "p:name". context.4 (http://jakarta.org/2001/XMLSchemainstance" xmlns:p="http://www.Web Tier by Christy XML Bean-Injection.springframework.4.

public class Main { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathRes ource( "context.core. import org. String.springframework. } public void setCompany(String company) { this. int age.net"/> </beans> Main.address = address.beans.p:email="girish@javabeat.io.xml")):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context. String email.xml")).springframework.xml"):-Creates a new ClassPathResource for ClassLoader .out.format("Name: %s\n" +"Age: %d\n" ):-This method formats an object to produce a string.xml is the file which is to be loaded.company = company. String company. Here %s:-is for accessing String value.println(demo). Some of the methods which are used here are as follows:XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("c ontext.java This is the file through which we are retrieving the property of the bean defined above. System.getBean("mybean"). import org. String address.factory.ClassPathResource. Inject demo = (Inject) beanFactory. } } class Inject { private private private private private String name. %d:-is for accessing Integer value.XmlBeanFactory.Here the context. public void setAddress(String address) { this.xml. } 47 .

name.net BUILD SUCCESSFUL (total time: 1 second) .jdbc. this. this.168.dbcp.jdbc.xsd"> <bean id="dataSource" class="org. } public void setAge(int age) { this.10.springframework.name = name.Driver"/> <property name="url" value="jdbc:mysql://192. } } Output of the Spring Injection Example program Nov 25.xml.springframework.mysql.commons.format("Name: %s\n" + "Age: %d\n" + "Address: %s\n" + "Company: %s\n" + "E-mail: %s".public void setEmail(String email) { this. } @Override public String toString() { return String. this.support.CommonsDbcpNativeJdbcExtracto r"/> 48 . this.address.org/schema/lang/spring-lang-2.jdbc. this.em ail).beans.75:3306/komal"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="lobHandler" class="org.net E-mail: girish@javabeat.age = age.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.support.0.nativejdbc.xml] Name: Girish Age: 24 Address: Noida Company: javabeat.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.factory. 2008 1:03:13 AM org.springframework.company. } public void setName(String name) { this.apache.springframework.age.email = email.lob.

xml".JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans> Main.getBean("dataSource"). This method executes multiple Sql updates on a single JDBC statement.ApplicationContext. } catch (Exception e) { e.class):ApplicationContext is the interface that is used to provide Bean factory methods for accessing application components. Here we created datasource for making connection to our xml document in which we have declared the bean.core.jdbc. import org. import javax. "delete from employee where EmployeeId =31" }).support. Main.core.xml and Main.jdbc.springframework.xml". } } } Output of the program 49 .DataSource. jt. Here we Creates an instance of this interface to access context.java ApplicationContext ac = new ClassPathXmlApplicationContext("context.java.<bean id="jdbcTemplate" class="org.getBean("dataSource"):-Data source is an Interface which provides a way for connecting to the physical data source.batchUpdate(new String[]{"update employee set departement = 'Finance#'". "delete from employeewhere EmployeeId =31" }):-With the use of this method we are executing two SQLquery simultaneously.out. DataSource source = (DataSource) ac. System.JdbcTemplate. import org. jt.ClassPathXmlApplicationContext.printStackTrace().springframework.println("Data updated successfully").batchUpdate(new String[]{"update employee set departement = 'Finance#'". JdbcTemplate jt = new JdbcTemplate(source). Main.context.springframework. import org. DataSource source = (DataSource) ac.sql.class).springframework.context. class Main { public static void main(String args[]) { try { ApplicationContext ac = new ClassPathXmlApplicationContext("context.

springframework. <bean id="parent" class="mybean" > <property name="name" value="javabeat.org/schema/beans/springbeans.0" encoding="UTF-8"?> <beans xmlns="http://www.org/schema/beans" xmlns:xsi="http://www.org/schema/beans http://www. parent="parent":-Specify that this bean is inheriting the properties of some other bean.net"/> </bean> <bean id="child" class="mybean" parent="parent"> <property name="address" value="Rohini"/> </bean> context.springframework.w3. <bean id="parent" class="mybean" >:-Creates a Parent bean which would be used as a template for creating other beans. <bean id="child" class="mybean" parent="parent">:-Creates a child bean which would be inheriting from the parent bean defined above.org/2001/XMLSchemainstance" xsi:schemaLocation=" http://www.Data updated successfully BUILD SUCCESSFUL (total time: 2 seconds) Inheritance in Spring • Read Introduction to Spring MVC Web Framework . Here we have created a simple bean and used this bean as a template for creating other beans.springframework. Here "mybean" is the name of the bean class which would be referred in the xml file with the id "parent". Byinheritance we mean a way of forming new classes using classes that have already been defined.net"/> </bean> <bean id="child" class="mybean" parent="parent"> <property name="address" value="Rohini"/> </bean> 50 . In the example given below we are going to tell about the inheritance in the Spring framework.xsd"> <bean id="parent" class="mybean" > <property name="name" value="javabeat.xml <?xml version="1.Web Tier by Christy Inheritance Demo.

public void setName(String name) { this. System.name = name.xml is the file which is to be loaded.springframework.xml")):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.append("Bean"):-This is the method of the class string Builder which appends the specified string to this character sequence. private String address.XmlBeanFactory. System.out.getBean("subchild")).core.xml. Some of the methods which are used here are as follows:XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("c ontext.println(bf.xml"):-Creates a new ClassPathResource for ClassLoader . } public void setAddress(String address) { this.address = address.beans. 51 .out.getBean("child")):-This method returns an instance of the bean named "child". of the given bean name.out.println("===============Inheritance demo================= "). stringBuilder.factory. which is shared or independent.ClassPathResource.io.springframework.getBean("child")).<bean id="subchild" class="mybean" parent="parent"/> </beans> Main. System. (bf.getBean("subchild")):-This method returns an instance of the bean named "subchild".println(bf. of the given bean name. import org.xml")).java This is the file through which we are retrieving the property of the bean defined above.Here the context. (bf. } } class mybean { private String name. which is shared or independent. public class Main { public static void main(String[] args) throws Exception { XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("contex t. import org.

their properties as well as their values. 2)bean behavioral configuration elements: Here we define the bean behavior that is bean initialization. 2008 3:39:29 AM org.factory. address=").append(". Required fields:1)class name: A class name is the implementation of the bean class that is described in the bean definition.net'.net'.springframework. stringBuilder. stringBuilder.xml.append("{name='"). stringBuilder. return stringBuilder. The tutorial given below describes you the way to make a spring web application that displays Hello World message on the Browser.xml] ===============Inheritancedemo================= Bean{name='javabeat. 52 . 3)constructor arguments and property values :-Defines the no of arguments and the property values that are to be set in the newly created bean.Web Tier by Christy Hello World Example using Spring. For that we have created a file called "applicationContext.beans. address=null} BUILD SUCCESSFUL (total time: 1 second) Spring Hello World Application • Read Introduction to Spring MVC Web Framework .append(name).} @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder().toString(). } } Output of the program Nov 25. stringBuilder.We have not defined any of these behavior in our context file since we haven't created any of the bean to be used.xml".XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context. address=Rohini} Bean{name='javabeat.append('}'). destruction methods etc.append("Bean"). Note:. which defines the bean name. dependencychecking mode.append(address).append('\'').

springframework. <?xml version="1.org/schema/tx" xsi:schemaLocation="http://www.5.springframework.springframework.org/schema/beans http://www.view.servlet.web.servlet.org/schema/beans/spring-beans-2.springframework.InternalResourceVi 53 .org/2001/XMLSchema-instance" xmlns:p="http://www.xsd"> <bean class="org.xsd http://www.org/schema/p" xmlns:aop="http://www.web. p:suffix=".springframework.htm">indexController </prop> </props> </property> </bean> <bean id="viewResolver" class="org.org/schema/aop http://www.springframework.org/schema/p" xmlns:aop="http://www.xsd"> </beans> dispatcher-servlet.springframework.org/schema/aop" xmlns:tx="http://www. p:viewName="index"Â />:This is the ParameterizableViewController.org/schema/beans/spring-beans-2.springframework.5.5. With the use of this we can map this name to an actualjsp page.w3.5.org/schema/aop/spring-aop-2.5.0" encoding="UTF-8"?> <beans xmlns="http://www.xsd http://www.xsd http://www.springframework.handler .5.springframework.0" encoding="UTF-8"?> <beans xmlns="http://www.xsd http://www.ControllerC lassNameHandlerMapping"/> <bean id="urlMapping" class="org. xml:-This is the file from which the mapping from actions to controllers is done .springframework.springframework.org/schema/tx http://www.springframework.servlet.w3.springframework.org/schema/aop" xmlns:tx="http://www.org/schema/tx http://www.org/schema/beans" xmlns:xsi="http://www.springframework.springframework. With the use of this controller we can view the index.org/schema/beans" xmlns:xsi="http://www.web.mvc. ControllerClassNameHandlerMapping class generate URL path mappings from the class names of the Controller.org/schema/aop http://www.springframework.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/tx/spring-tx-2.springframework.org/schema/beans http://www.springframework.<?xml version="1.support.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/index.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop/spring-aop-2.jsp"Â />:-This is InternalResourceViewResolver.org/schema/tx/spring-tx-2.springframework.We have used ControllerClassNameHandlerMapping and SimpleUrlHandlerMapping classes to do such mapping.SimpleUrlHandlerMapping maps URLs to the request handler beans.

01 Trans itional//EN" "http://www.htm").ParameterizableView Controller" p:viewName="index" /> </beans> redirect.sendRedirect("index. <%@page contentType="text/html" pageEncoding="UTF8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. %>:-This is a method of Interface HttpServletResponse that is used to sends a temporary redirect response to the client using the specified redirect location.htm").jsp" /> <bean name="indexController" class="org. charset=UTF-8"> <title>Hello World-Spring</title> <h1>Hello World-Spring</h1> <hr></hr> </head> <body> <h2>Hello World</h2> </body> </html> Calling Constructor in Spring • Read Introduction to Spring MVC Web Framework .jsp:-This is the page in which the message is to be displayed.springframework.dtd"> <html> <head> <meta http-equiv="Content-Type" content="t ext/html.ewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=". Steps to declare Constructor Injection: 1)Set the constructor declaration 54 . %> index.xml file.sendRedirect("index.mvc. Declaring constructor injection in the Spring framework is generally done in the bean section of the configuration file that is the context.w3.jsp:<% response.servlet.Web Tier by Christy In the given example you will be learning about a constructor and how to call a constructor in the Spring. <%@page contentType="text/html" pageEncoding="UTF8"%> <% response.web.org/TR/html4/loose.

org/schema/beans" xmlns:xsi="http://www.springframework.w3.2)Pass the value to the constructor.org/schema/util/springutil. <entry key="CompanyName" value="javabeat.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> </bean> <bean id="company" class="Companyinformation"> <property name="encyclopedia" ref="mybean"/> </bean> </beans> Here is the file named Main.java through which we are retrieving the properties of the bean which we have defined in the above file i. Here we have pass "javabeat.net"/> <entry key="Address" value="Rohini"/> </util:map> </constructor-arg> <constructor-arg>:-This is the way to declare the constructor injection consisting of arguments.0" encoding="UTF-8"?> <beans xmlns="http://www. The use of this injection is to tell the container that the application wants to use the Constructor Injection. <constructor-arg> <util:map> <entry key="CompanyName" value="javabeat. This tutorial describes the way of defining constructor in the xml document and retrieving the values defined in the constructor using java file.net " as the company name.org/schema/beans/springbeans.net"/>:-Passing the value to the constructor is usually done through the <value>element.org/schema/beans http://www. context.xsd"> <bean id="encyclopedia" name="mybean" class="Configure"> <constructor-arg> <util:map> <entry key="CompanyName" value="javabeat.springframework.springframework.org/schema/util" xsi:schemaLocation=" http://www.xml <?xml version="1.xml 55 .springframework. context.org/schema/util http://www.xsd http://www.springframework.e.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.

56 .factory.XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("c ontext. } interface Detail { } String find(String entry). Main.detail.valueOf(name).util.xml is the file which is to be loaded.Here the context.out. String address().getBean("company").find("Address"). org.find("CompanyName"). System. System.Map.springframework.beans.springframework.valueOf(add).detail = d.Assert. company mycomp = (company) beanFactory.println("Address of the company is: " + mycomp.Name()).out. return String. } } interface company { String Name().core. class Companyinformation implements company { private Detail detail.ClassPathResource.java import import import import java. org.xml. public class Main { public static void main(String[] a) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathRes ource("context.XmlBeanFactory.detail. } public void setEncyclopedia(Detail d) { this.addres s()).println("Name of the company is: " + mycomp. return String.io.xml")).xml"):-Creates a new ClassPathResource for ClassLoader . public String Name() { String name = this. org.xml")):-Here we are creating an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context. } public String address() { String add = this.util.springframework.

Here the property name is "name"and its value is "javabeat.} } class Configure implements Detail { private Map map. } } Output of the program Nov 26.map.beans. public Configure(Map map) { Assert. init-method="init":-Specify the init method named "init" in the configuration file. "Arguments cannot be null.xml] Name of the company is: javabeat.notNull(map.net Address of the company is: Rohini BUILD SUCCESSFUL (total time: 1 second) init Method in Spring • Read Introduction to Spring MVC Web Framework .").net</value>:-Here the <property> element is used to declare the attributes and to pass the desired value to the property element.factory. the <value> element is used.springframework.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.Web Tier by Christy Calling Bean using init() method in Spring. <bean id="mybean" class="Bean" init-method="init"> <property name="name"> 57 .map = map. this section describes the way to initialize a bean through its lifecycleevents using the init() method . } public String find(String s) { return (String) this. <property name="name"> <value>javabeat.get(s).net".Here we have defined the property and values of the bean using the init method as shown below:<bean id="mybean" class="Bean" init-method="init">:-Here "Bean" is the name of the bean class which would be referred in the xml file with the id "mybean". this. 2008 12:48:55 AM org.

java import import import import org.xml.io. public void setName(String name) { 58 .springframework. org. address = null.BeanCreationException. org. SimpleBean.<value>javabeat. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("init Method.FileSystemResource.org/dtd/spring-beans.factory. type = null.XmlBeanFactory.java through which we are retrieving the properties of the bean which we havedefined in the above file i.net</value> </property> <property name="address"> <value>Rohini</value> </property> <property name="type"> <value>Software Development Company</value> </property> </bean> </beans> Here is the file named SimpleBean. name = null.springframework.factory.beans.springframework.beans.beans.xml.core.dtd"> <beans> <bean id="mybean" class="Bean" init-method="init"> <property name="name"> <value>javabeat.e. initMethod.factory. org.springframework.BeanFactory.net</value> </property> <property name="address"> <value>Rohini</value> </property> <property name="type"> <value>Software Development Company</value> </property> </bean> initMethod. public class Bean { private private private private static String String String final String DEFAULT_NAME = "Girish".xml")):-Creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document.xml <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.

} catch (BeanCreationException ex) { System. } public void setType(String type) { this.println("Using default name"). factory).out.xml")). type = DEFAULT_NAME. name = DEFAULT_NAME.out.out.out. } if (type == null) { System. } public void init() { System. BeanFactory factory) { try { Bean bean = (Bean) factory.println("Using default name"). } private static Bean getBean(String beanName.address = address. System. } } public String toString() { return "Name: " + name + "\nAddress: " + address + "\nType: " + type .println(bean). Bean Bean1 = getBean("mybean".println("Initializing bean").println("Using default name"). } public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new FileSystemResource( "initMethod.out.println("An error occured in bean configuration: " + ex. } if (address == null) { System.getMessage()).name = name. if (name == null) { System. return bean. address = DEFAULT_NAME. } } } Output of the program Initializing bean 59 . } public void setAddress(String address) { this.getBean(beanName).type = type. return null.out.this.

context.springframework.net Address: Rohini Type: Software Development Company Bean life cycle in spring • Read Introduction to Spring MVC Web Framework .xsd"> <bean id="Mybean" class="Bean"> <property name="company" value="Name"/> <property name="value" value="javabeat.springframework. context.Web Tier by Christy <bean id="Mybean" class="Bean"> <property name="company" value="Name"/> <property name="value" value="javabeat.e.0" encoding="UTF-8"?> <beans xmlns="http://www.org/schema/beans" xmlns:xsi="http://www.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.Here the context.xml XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("c ontext.xml is the file which is to be loaded.springframework. <property name="company" value="Name"/>:-Declares the property name of the bean and its value.org/schema/beans/springbeans.org/schema/beans http://www.xml")):-Here we are creating an instance of the XmlBeanFactory which is used to read bean definition from an XML document new ClassPathResource("context.w3.xml <?xml version="1.net"/> </bean> </beans> Here is the file named Main.xml"):-Creates a new ClassPathResource for ClassLoader .java through which we are retrieving the properties of the bean which we have defined in the above file i.Name: javabeat. 60 .net"/> </bean> Here "Bean" is the name of the bean class which would be further referred in the xml file with the id "MyBean".

company.println(factory.out. System.getBean("Mybean")).core.company = company. } protected final String getValue() { return this.factory.xml file.springframework.factory. getValue()).xml.company..io.ClassPathResource. } 61 . public void setCompany(String company) { this. public final void afterPropertiesSet() throws Exception { } public final void setValue(String value) { this.value = value. getValue()). this. The use of this interface here is to do some post processing actions when all the properties have been set by the Bean Factory. import org. public class Main { public static void main(String[] args) throws Exception { XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context. Main.springframework.InitializingBean. @Override public String toString() { is.format("%s : \"%s\"".format("%s : \"%s\"".springframework. th Here the method toString() is overridden which is returning the the company name and value that has been defined in the context.java import org. import org. } class Bean extends BeanSupport { private String company.value.class BeanSupport implements InitializingBean :-Here the InitializingBean interface is implemented by bean class. } return String.XmlBeanFactory. } @Override public String toString() { return String.xml")).beans.beans. } } } class BeanSupport implements InitializingBean { private String value.

net" BUILD SUCCESSFUL (total time: 1 second) 62 .xml.beans.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.} Output of the program Nov 25.springframework.factory. 2008 5:25:41 AM org.xml] Name : "javabeat.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->