2. Introduction to Spring Framework (2024)

2.Introduction to Spring Framework

Spring Framework is a Java platform that provides comprehensive infrastructure supportfor developing Java applications. Spring handles the infrastructure so you can focus onyour application.

Spring enables you to build applications from "plain old Java objects" (POJOs) and toapply enterprise services non-invasively to POJOs. This capability applies to the JavaSE programming model and to full and partial Java EE.

Examples of how you, as an application developer, can use the Spring platform advantage:

2.1Dependency Injection and Inversion of Control

Background

"The question is, what aspect of control are [they] inverting?" Martin Fowler posedthis question about Inversion of Control (IoC) on his site in 2004. Fowler suggestedrenaming the principle to make it more self-explanatory and came up with DependencyInjection.

For insight into IoC and DI, refer to Fowler’s article athttp://martinfowler.com/articles/injection.html.

Java applications — a loose term that runs the gamut from constrained applets to n-tierserver-side enterprise applications — typically consist of objects that collaborate toform the application proper. Thus the objects in an application have dependencies oneach other.

Although the Java platform provides a wealth of application development functionality,it lacks the means to organize the basic building blocks into a coherent whole, leavingthat task to architects and developers. True, you can use design patterns suchas Factory, Abstract Factory, Builder, Decorator, and Service Locatorto compose the various classes and object instances that make up an application.However, these patterns are simply that: best practices given a name, with a descriptionof what the pattern does, where to apply it, the problems it addresses, and so forth.Patterns are formalized best practices that you must implement yourself in yourapplication.

The Spring Framework Inversion of Control (IoC) component addresses this concern byproviding a formalized means of composing disparate components into a fully workingapplication ready for use. The Spring Framework codifies formalized design patterns asfirst-class objects that you can integrate into your own application(s). Numerousorganizations and institutions use the Spring Framework in this manner to engineerrobust, maintainable applications.

2.2Modules

The Spring Framework consists of features organized into about 20 modules. These modulesare grouped into Core Container, Data Access/Integration, Web, AOP (Aspect OrientedProgramming), Instrumentation, and Test, as shown in the following diagram.

Figure2.1.Overview of the Spring Framework

2.Introduction to Spring Framework (1)


2.2.1Core Container

The Core Container consists of the Core, Beans, Context, andExpression Language modules.

The Core and Beans modules provide the fundamental parts ofthe framework, including the IoC and Dependency Injection features. The BeanFactory isa sophisticated implementation of the factory pattern. It removes the need forprogrammatic singletons and allows you to decouple the configuration and specificationof dependencies from your actual program logic.

The Context module builds on the solid base provided by theCore and Beans modules: it is a means to access objects in aframework-style manner that is similar to a JNDI registry. The Context module inheritsits features from the Beans module and adds support for internationalization (using, forexample, resource bundles), event-propagation, resource-loading, and the transparentcreation of contexts by, for example, a servlet container. The Context module alsosupports Java EE features such as EJB, JMX ,and basic remoting. The ApplicationContextinterface is the focal point of the Context module.

The Expression Language module provides a powerful expressionlanguage for querying and manipulating an object graph at runtime. It is an extension ofthe unified expression language (unified EL) as specified in the JSP 2.1 specification.The language supports setting and getting property values, property assignment, methodinvocation, accessing the context of arrays, collections and indexers, logical andarithmetic operators, named variables, and retrieval of objects by name from Spring’sIoC container. It also supports list projection and selection as well as common listaggregations.

2.2.2Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS andTransaction modules.

The JDBC module provides a JDBC-abstraction layer that removes theneed to do tedious JDBC coding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popularobject-relational mapping APIs, including JPA, JDO, andHibernate. Using the ORM package you can use all of these O/R-mappingframeworks in combination with all of the other features Spring offers, such as the simpledeclarative transaction management feature mentioned previously.

The OXM module provides an abstraction layer that supports Object/XML mappingimplementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service (JMS) module contains features for producing andconsuming messages.

The Transaction module supports programmatic and declarative transactionmanagement for classes that implement special interfaces and for all your POJOs (plainold Java objects).

The Web layer consists of the Web, Web-Servlet, WebSocket and Web-Portlet modules.

Spring’s Web module provides basic web-oriented integration features such asmultipart file-upload functionality and the initialization of the IoC container usingservlet listeners and a web-oriented application context. It also contains theweb-related parts of Spring’s remoting support.

The Web-Servlet module contains Spring’s model-view-controller(MVC) implementation for web applications. Spring’s MVCframework provides a clean separation between domain model code and web forms, andintegrates with all the other features of the Spring Framework.

The Web-Portlet module provides the MVC implementation to be used in a portletenvironment and mirrors the functionality of Web-Servlet module.

2.2.4AOP and Instrumentation

Spring’s AOP module provides an AOP Alliance-compliantaspect-oriented programming implementation allowing you to define, for example,method-interceptors and pointcuts to cleanly decouple code that implements functionalitythat should be separated. Using source-level metadata functionality, you can alsoincorporate behavioral information into your code, in a manner similar to that of .NETattributes.

The separate Aspects module provides integration with AspectJ.

The Instrumentation module provides class instrumentation support and classloaderimplementations to be used in certain application servers.

2.2.5Test

The Test module supports the testing of Spring components with JUnit or TestNG. Itprovides consistent loading of Spring ApplicationContexts and caching of those contexts.It also provides mock objects that you can use to test your code in isolation.

2.3Usage scenarios

The building blocks described previously make Spring a logical choice in many scenarios,from applets to full-fledged enterprise applications that use Spring’s transactionmanagement functionality and web framework integration.

Figure2.2.Typical full-fledged Spring web application

2.Introduction to Spring Framework (2)


Spring’s declarative transaction management features makethe web application fully transactional, just as it would be if you used EJBcontainer-managed transactions. All your custom business logic can be implemented withsimple POJOs and managed by Spring’s IoC container. Additional services include supportfor sending email and validation that is independent of the web layer, which lets youchoose where to execute validation rules. Spring’s ORM support is integrated with JPA,Hibernate and and JDO; for example, when using Hibernate, you can continue to useyour existing mapping files and standard Hibernate SessionFactory configuration. Formcontrollers seamlessly integrate the web-layer with the domain model, removing the needfor ActionForms or other classes that transform HTTP parameters to values for yourdomain model.

Figure2.3.Spring middle-tier using a third-party web framework

2.Introduction to Spring Framework (3)


Sometimes circ*mstances do not allow you to completely switch to a different framework.The Spring Framework does not force you to use everything within it; it is not anall-or-nothing solution. Existing front-ends built with Struts, Tapestry, JSFor other UI frameworks can be integrated with a Spring-based middle-tier, which allowsyou to use Spring transaction features. You simply need to wire up your business logicusing an ApplicationContext and use a WebApplicationContext to integrate your weblayer.

Figure2.4.Remoting usage scenario

2.Introduction to Spring Framework (4)


When you need to access existing code through web services, you can use Spring’sHessian-, Burlap-, Rmi- or JaxRpcProxyFactory classes. Enabling remote access toexisting applications is not difficult.

Figure2.5.EJBs - Wrapping existing POJOs

2.Introduction to Spring Framework (5)


The Spring Framework also provides an access and abstraction layer forEnterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them instateless session beans for use in scalable, fail-safe web applications that might needdeclarative security.

2.3.1Dependency Management and Naming Conventions

Dependency management and dependency injection are different things. To get those nicefeatures of Spring into your application (like dependency injection) you need toassemble all the libraries needed (jar files) and get them onto your classpath atruntime, and possibly at compile time. These dependencies are not virtual componentsthat are injected, but physical resources in a file system (typically). The process ofdependency management involves locating those resources, storing them and adding them toclasspaths. Dependencies can be direct (e.g. my application depends on Spring atruntime), or indirect (e.g. my application depends on commons-dbcp which depends oncommons-pool). The indirect dependencies are also known as "transitive" and it isthose dependencies that are hardest to identify and manage.

If you are going to use Spring you need to get a copy of the jar libraries that comprisethe pieces of Spring that you need. To make this easier Spring is packaged as a set ofmodules that separate the dependencies as much as possible, so for example if you don’twant to write a web application you don’t need the spring-web modules. To refer toSpring library modules in this guide we use a shorthand naming convention spring-* orspring-*.jar, where * represents the short name for the module (e.g. spring-core,spring-webmvc, spring-jms, etc.). The actual jar file name that you use is normallythe module name concatenated with the version number(e.g. spring-core-4.0.9.RELEASE.jar).

Each release of the Spring Framework will publish artifacts to the following places:

  • Maven Central, which is the default repository that Maven queries, and does notrequire any special configuration to use. Many of the common libraries that Springdepends on also are available from Maven Central and a large section of the Springcommunity uses Maven for dependency management, so this is convenient for them. Thenames of the jars here are in the form spring-*-<version>.jar and the Maven groupIdis org.springframework.
  • In a public Maven repository hosted specifically for Spring. In addition to the finalGA releases, this repository also hosts development snapshots and milestones. The jarfile names are in the same form as Maven Central, so this is a useful place to getdevelopment versions of Spring to use with other libraries deployed in Maven Central.This repository also contains a bundle distribution zip file that contains all Springjars bundled together for easy download.

So the first thing you need to decide is how to manage your dependencies: we generallyrecommend the use of an automated system like Maven, Gradle or Ivy, but you can also doit manually by downloading all the jars yourself. We provide detailed instructions laterin this chapter.

Spring Dependencies and Depending on Spring

Although Spring provides integration and support for a huge range of enterprise andother external tools, it intentionally keeps its mandatory dependencies to an absoluteminimum: you shouldn’t have to locate and download (even automatically) a large numberof jar libraries in order to use Spring for simple use cases. For basic dependencyinjection there is only one mandatory external dependency, and that is for logging (seebelow for a more detailed description of logging options).

Next we outline the basic steps needed to configure an application that depends onSpring, first with Maven and then with Gradle and finally using Ivy. In all cases, ifanything is unclear, refer to the documentation of your dependency management system, orlook at some sample code - Spring itself uses Gradle to manage dependencies when it isbuilding, and our samples mostly use Gradle or Maven.

Maven Dependency Management

If you are using Maven for dependency management you don’t evenneed to supply the logging dependency explicitly. For example, to create an applicationcontext and use dependency injection to configure an application, your Maven dependencieswill look like this:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.9.RELEASE</version> <scope>runtime</scope> </dependency></dependencies>

That’s it. Note the scope can be declared as runtime if you don’t need to compileagainst Spring APIs, which is typically the case for basic dependency injection usecases.

The example above works with the Maven Central repository. To use the Spring Mavenrepository (e.g. for milestones or developer snapshots), you need to specify therepository location in your Maven configuration. For full releases:

<repositories> <repository> <id>io.spring.repo.maven.release</id> <url>http://repo.spring.io/release/</url> <snapshots><enabled>false</enabled></snapshots> </repository></repositories>

For milestones:

<repositories> <repository> <id>io.spring.repo.maven.milestone</id> <url>http://repo.spring.io/milestone/</url> <snapshots><enabled>false</enabled></snapshots> </repository></repositories>

And for snapshots:

<repositories> <repository> <id>io.spring.repo.maven.snapshot</id> <url>http://repo.spring.io/snapshot/</url> <snapshots><enabled>true</enabled></snapshots> </repository></repositories>

Maven "Bill Of Materials" Dependency

It is possible to accidentally mix different versions of Spring JARs when using Maven.For example, you may find that a third-party library, or another Spring project,pulls in a transitive dependency to an older release. If you forget to explicitly declarea direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM)dependency. You can import the spring-framework-bom in your dependencyManagementsection to ensure that all spring dependencies (both direct and transitive) are atthe same version.

<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>4.0.9.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>

An added benefit of using the BOM is that you no longer need to specify the <version>attribute when depending on Spring Framework artifacts:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency><dependencies>

Gradle Dependency Management

To use the Spring repository with the Gradle build system,include the appropriate URL in the repositories section:

repositories { mavenCentral() // and optionally... maven { url "http://repo.spring.io/release" }}

You can change the repositories URL from /release to /milestone or /snapshot asappropriate. Once a repository has been configured, you can declare dependencies in theusual Gradle way:

dependencies { compile("org.springframework:spring-context:4.0.9.RELEASE") testCompile("org.springframework:spring-test:4.0.9.RELEASE")}

Ivy Dependency Management

If you prefer to use Ivy to manage dependencies then thereare similar configuration options.

To configure Ivy to point to the Spring repository add the following resolver to yourivysettings.xml:

<resolvers> <ibiblio name="io.spring.repo.maven.release" m2compatible="true" root="http://repo.spring.io/release/"/></resolvers>

You can change the root URL from /release/ to /milestone/ or /snapshot/ asappropriate.

Once configured, you can add dependencies in the usual way. For example (in ivy.xml):

<dependency org="org.springframework" name="spring-core" rev="4.0.9.RELEASE" conf="compile->runtime"/>

Distribution Zip Files

Although using a build system that supports dependency management is the recommendedway to obtain the Spring Framework, it is still possible to download a distributionzip file.

Distribution zips are published to the Spring Maven Repository (this is just for ourconvenience, you don’t need Maven or any other build system in order to download them).

To download a distribution zip open a web browser tohttp://repo.spring.io/release/org/springframework/spring and select the appropriatesubfolder for the version that you want. Distribution files end -dist.zip, for examplespring-framework-4.0.9.RELEASE-RELEASE-dist.zip. Distributions are also publishedfor milestones andsnapshots.

2.3.2Logging

Logging is a very important dependency for Spring because a) it is the only mandatoryexternal dependency, b) everyone likes to see some output from the tools they areusing, and c) Spring integrates with lots of other tools all of which have also madea choice of logging dependency. One of the goals of an application developer is often tohave unified logging configured in a central place for the whole application, includingall external components. This is more difficult than it might have been since there are somany choices of logging framework.

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). Wecompile against JCL and we also make JCL Log objects visible for classes that extendthe Spring Framework. It’s important to users that all versions of Spring use the samelogging library: migration is easy because backwards compatibility is preserved evenwith applications that extend Spring. The way we do this is to make one of the modulesin Spring depend explicitly on commons-logging (the canonical implementation of JCL),and then make all the other modules depend on that at compile time. If you are usingMaven for example, and wondering where you picked up the dependency oncommons-logging, then it is from Spring and specifically from the central modulecalled spring-core.

The nice thing about commons-logging is that you don’t need anything else to make yourapplication work. It has a runtime discovery algorithm that looks for other loggingframeworks in well known places on the classpath and uses one that it thinks isappropriate (or you can tell it which one if you need to). If nothing else is availableyou get pretty nice looking logs just from the JDK (java.util.logging or JUL for short).You should find that your Spring application works and logs happily to the console outof the box in most situations, and that’s important.

Not Using Commons Logging

Unfortunately, the runtime discovery algorithm in commons-logging, while convenientfor the end-user, is problematic. If we could turn back the clock and start Spring nowas a new project it would use a different logging dependency. The first choice wouldprobably be the Simple Logging Facade for Java ( SLF4J), which isalso used by a lot of other tools that people use with Spring inside their applications.

There are basically two ways to switch off commons-logging:

  1. Exclude the dependency from the spring-core module (as it is the only module thatexplicitly depends on commons-logging)
  2. Depend on a special commons-logging dependency that replaces the library withan empty jar (more details can be found in theSLF4J FAQ)

To exclude commons-logging, add the following to your dependencyManagement section:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.9.RELEASE</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency></dependencies>

Now this application is probably broken because there is no implementation of the JCLAPI on the classpath, so to fix it a new one has to be provided. In the next section weshow you how to provide an alternative implementation of JCL using SLF4J as an example.

Using SLF4J

SLF4J is a cleaner dependency and more efficient at runtime than commons-loggingbecause it uses compile-time bindings instead of runtime discovery of the other loggingframeworks it integrates. This also means that you have to be more explicit about whatyou want to happen at runtime, and declare it or configure it accordingly. SLF4Jprovides bindings to many common logging frameworks, so you can usually choose one thatyou already use, and bind to that for configuration and management.

SLF4J provides bindings to many common logging frameworks, including JCL, and it alsodoes the reverse: bridges between other logging frameworks and itself. So to use SLF4Jwith Spring you need to replace the commons-logging dependency with the SLF4J-JCLbridge. Once you have done that then logging calls from within Spring will be translatedinto logging calls to the SLF4J API, so if other libraries in your application use thatAPI, then you have a single place to configure and manage logging.

A common choice might be to bridge Spring to SLF4J, and then provide explicit bindingfrom SLF4J to Log4J. You need to supply 4 dependencies (and exclude the existingcommons-logging): the bridge, the SLF4J API, the binding to Log4J, and the Log4Jimplementation itself. In Maven you would do that like this

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.9.RELEASE</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency></dependencies>

That might seem like a lot of dependencies just to get some logging. Well it is, but itis optional, and it should behave better than the vanilla commons-logging withrespect to classloader issues, notably if you are in a strict container like an OSGiplatform. Allegedly there is also a performance benefit because the bindings are atcompile-time not runtime.

A more common choice amongst SLF4J users, which uses fewer steps and generates fewerdependencies, is to bind directly to Logback. This removes theextra binding step because Logback implements SLF4J directly, so you only need to dependon two libraries not four ( jcl-over-slf4j and logback). If you do that you mightalso need to exclude the slf4j-api dependency from other external dependencies (notSpring), because you only want one version of that API on the classpath.

Using Log4J

Many people use Log4j as a logging framework forconfiguration and management purposes. It’s efficient and well-established, and in factit’s what we use at runtime when we build and test Spring. Spring also provides someutilities for configuring and initializing Log4j, so it has an optional compile-timedependency on Log4j in some modules.

To make Log4j work with the default JCL dependency ( commons-logging) all you need todo is put Log4j on the classpath, and provide it with a configuration file (log4j.properties or log4j.xml in the root of the classpath). So for Maven users thisis your dependency declaration:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.9.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency></dependencies>

And here’s a sample log4j.properties for logging to the console:

log4j.rootCategory=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%nlog4j.category.org.springframework.beans.factory=DEBUG
Runtime Containers with Native JCL

Many people run their Spring applications in a container that itself provides animplementation of JCL. IBM Websphere Application Server (WAS) is the archetype. Thisoften causes problems, and unfortunately there is no silver bullet solution; simplyexcluding commons-logging from your application is not enough in most situations.

To be clear about this: the problems reported are usually not with JCL per se, or evenwith commons-logging: rather they are to do with binding commons-logging to anotherframework (often Log4J). This can fail because commons-logging changed the way they dothe runtime discovery in between the older versions (1.0) found in some containers andthe modern versions that most people use now (1.1). Spring does not use any unusualparts of the JCL API, so nothing breaks there, but as soon as Spring or your applicationtries to do any logging you can find that the bindings to Log4J are not working.

In such cases with WAS the easiest thing to do is to invert the class loader hierarchy(IBM calls it "parent last") so that the application controls the JCL dependency, notthe container. That option isn’t always open, but there are plenty of other suggestionsin the public domain for alternative approaches, and your mileage may vary depending onthe exact version and feature set of the container.

2. Introduction to Spring Framework (2024)
Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5717

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.