What Is Spring Framework?

WHAT IS SPRING FRAMEWORK?

Spring Framework is an application container for Java that supplies many useful features, such as Inversion of Control, Dependency Injection, abstract data access, transaction management, and more. It was conceived in 2002 in response to industry complaints that the Java EE specification was sorely lacking and very difficult to use. Its first major release in 2004 was a game changer for Java EE applications and was followed by 2.0 in 2006, 2.5 in 2007, 3.0 in 2009, 3.1 in 2011, and 3.2 in 2012. Released in December 2013, the latest major version, Spring Framework 4.0, contains many enhancements, including support for Java SE 8, Java EE 7, WebSockets, and Groovy 2.

Though Spring Framework rose from the Enterprise Edition world, it is by no means strictly restricted to an EE environment. Often considered an alternative to or supplement for Enterprise JavaBeans (EJB, a Java EE server-side component for building enterprise applications in a modular fashion using encapsulated Beans), the Spring Framework container can run in any Java EE Application Server, Java EE Web Container, or Java SE standalone application (including server daemons and desktop applications).

EJB, on the other hand, is an Application Server-specific framework not found in desktop applications or even Web Containers such as Apache Tomcat and Jetty. Spring Framework is more than just a replacement for EJB, however; it provides many features that to this day Java EE still does not have replacements for. Over the years, Spring has evolved from a framework to a community, spawning many related projects such as Spring Security (which you learn about in Part IV of  Wrox’s Professional Java for Web Applications), Spring Data (which you learn about in Part III of Wrox’s Professional Java for Web Applications), Spring Integration, Spring Batch, Spring Mobile, Spring for Android, Spring Social, Spring Boot, and Spring.NET (the C# .NET port of Spring Framework), just to name a few.

To be sure, Spring Framework is not a requirement to develop rich Java web applications. You can create full-featured web applications with everything you have learned in this book up to this point. Spring Framework is a productivity framework: It makes developing applications of all types in a rapid way with modular concepts and testable code easier. It abstracts away the concepts of “requests” and “responses” and enables you to write application code that can be utilized from many different interfaces. When used properly, Spring Framework is the most powerful tool in your Java development toolbox.

Inversion of Control and Dependency Injection

One of Spring Framework’s core features is support for the closely related concepts of Inversion of Control (IoC) and Dependency Injection (DI). IoC is a software design pattern whereby an assembler, in this case Spring Framework, binds object coupling at run time instead of compile time. When some component of program logic, Service A for example, depends on another component of program logic, Service B, that dependency is fulfilled when the application runs instead of Service A instantiating Service B directly (which would be bound at compile time). This enables application developers to program against a set of interfaces, which can be swapped out in different environments without recompiling the code. One place this is handy is in a testing environment: “Mock” or “test” services can be provided while running unit tests; then the same code can be deployed to a production environment with more “real” services.

Though this can theoretically be achieved in any number of ways, DI is the most common technique. Using DI, a piece of program code (in Spring Framework, a class) declares that it depends on another piece of program code (an interface), and at run time the assembler injects an instance (usually but not always a singleton) of that dependency.

Aspect-Oriented Programming

Because Spring Framework handles the instantiation and injection of dependencies, it can wrap instances of the dependencies it injects to decorate method calls with other behavior. For example, using Spring Security you can annotate methods to indicate security restrictions placed on those methods, and Spring Framework wraps those method calls with the security checks necessary to fulfill those security restrictions. You can also define your own cross-cutting concerns using aspects, and Spring Framework decorates all the appropriate methods with these concerns. Cross-cutting concerns are concerns (such as security concerns) that affect multiple components of a program, often without regard to what those components are. Aspect-oriented programming is a complement to object-oriented programming that enables application of these concerns through the definition of aspects, which specify how and when to apply the concerns. Spring Framework provides extensive tools for aspect-oriented programming, which you will learn about throughout the rest of the book.

Data Access and Transaction Management

Spring Framework provides a set of data access tools that simplify the extraction and persistence of Java objects in relational databases. Though these features make unit testing data access drastically easier, some vendor-specify SQL is still required. Spring Framework also provides extensive support for the Java Persistence API (JPA) and object-relational mappers such as Hibernate ORM, which you explore in Part III of this book. Through the Spring Data project, persisting objects in relational databases, and NoSQL databases such as MongoDB and Redis, becomes a simple task. Finally, Spring Framework supports a declarative transactional model whereby execution of an annotated method is wrapped within a transaction and rolled back if the method throws an exception. This is achieved using Spring Framework’s AOP support.

Application Messaging

In any application, messaging is an important concern that needs addressing. For example, certain parts of a program may need to know when another part of the program performs a specified action. The part of the program performing this action could simply depend on the parts interested in the action and call methods on all of them to notify them, but that type of tight coupling is hard to maintain and can get very messy quickly.

Spring Framework provides a loosely coupled messaging system that uses the publish-subscribe pattern: Components in a system announce that they are interested in certain messages by subscribing to them, and the producers of these messages publish the messages without caring who is subscribed. This is essentially how Twitter works: People who have interesting (or perhaps noninteresting) things to say tweet those things, and other people who are interested in those types of tweets follow them. Using Spring Framework, a Spring-managed bean subscribes to a particular message type by implementing a generic interface, and other Spring-managed objects publish those messages to Spring Framework, which delivers them to the subscribed parties. This system can be extended and configured to deliver messages across a cluster of applications as well.

Model-View-Controller Pattern for Web Applications

Spring Framework features a model-view-controller (MVC) pattern framework that simplifies the process of creating interactive web applications. Instead of manually dealing with the complexities of Servlets,  

HttpServletRequest

s,  

HttpServletResponse

s, and forwarding to JSPs, Spring handles these tasks for you. Each method in a controller class is mapped to a different request URL, method, or other property of a request. The model is passed from the controller to the view in the form of a 

Map<String, Object>

. The 

View

or view name (

String

) returned from the controller method causes Spring to forward to the appropriate JSP view. Request and URL path parameters are automatically converted to primitive or complex controller method arguments.

In addition to typical HTML views, Spring can automatically generate plain text views and file download views and XML or JSON entity views. Through all these features, Spring Framework greatly simplifies working in a Servlet container.

WHY SPRING FRAMEWORK?

The Spring Framework’s feature set and simplification of the Servlet API are not the only advantages of Spring Framework. The patterns it encourages, provide several benefits that you can undoubtedly appreciate as you strive to create powerful web applications.

Logical Code Groupings

Consider some of the more complex Servlets you create. Each has a single 

doGet

or 

doPost

method, or perhaps both, containing many 

if

statements or 

switch

blocks responsible for routing the request to any number of methods within the Servlet. In a significantly more complicated enterprise application, you would quickly find this pattern becoming unmanageable and extremely difficult to test. A Servlet handling user profiles, for example, could have dozens of methods, each with a different route logic established in the 

doGet

or 

doPost

method.

A possible solution might be to create dozens of Servlets instead. Although this would result in a more testable and maintainable code base, the number of Servlets could quickly become as unmanageable as the number of logic branches were previously. If your application contains hundreds of features, each with dozens of pages, you would quickly realize a code base ballooning to thousands of tiny Servlets, which, to many developers, is equally unwanted. If your Servlets could be mapped down to the individual method level instead of only at the class, many problems would be solved.

Using Spring’s Web MVC framework, a controller class acts very much like a Servlet with method-level mappings. Each method can have a distinct mapping to a particular URL, request method, parameter existence, header value, content type, and/or expected response type. While your unit tests focus on testing the small units of code that are your controller methods, controller classes can contain many mapped methods that are logically grouped together. Returning to the user profile example, the controller could have dozens of mapped methods representing the different actions that can be taken on user profiles, but no 

doGet

or 

doPost

method is necessary to route requests to the proper methods. Spring Framework handles all of this analysis and routing for you.

Multiple User Interfaces Utilizing One Code Base

In a real-world scenario, you may be asked to create an advanced application with thousands of features that should be accessible from desktop applications, web browsers, mobile web browsers, RESTful web services, and SOAP web services. Using only Servlets, this task would quickly become daunting. You would eventually end up duplicating a lot of code or creating your own system in which business logic was abstracted into a set of other classes used from many user interfaces.

Fortunately, Spring Framework provides just such a system, tested and ready for you to use with very little effort. Using Spring, business logic becomes encapsulated in a set of business objects called services. These services perform operations common to all user interfaces, such as ensuring that certain entity properties are properly specified. Your application contains a different set of controllers and views for each user interface, and these use the common business objects to perform critical operations. Controllers, then, are necessary to perform only user interface-specific operations, such as translating form submissions or JSON request bodies into entities and displaying the appropriate view to the user. Unit testing becomes easier, code is reused, and very little effort is necessary to achieve both.

UNDERSTANDING APPLICATION CONTEXTS

The Spring Framework container comes in the form of one or more application contexts, represented by the 

org.springframework.context.ApplicationContext

interface. An application context manages a set of beans, Java objects that perform business logic, execute tasks, persist and retrieve persisted data, respond to HTTP requests, and more. Spring-managed beans are automatically eligible for dependency injection, message notification, scheduled method execution, bean validation, and other crucial Spring services.

A Spring application always has at least one application context, and sometimes that’s all it needs. However, it can also have a hierarchy of multiple application contexts. In such a hierarchy, any Spring-managed beans have access to beans in the same application context, in the parent application context, in the parent’s parent application context, and so forth. They do not have access to beans in sibling or child application contexts. This is useful for defining a set of shared application components while isolating other application components from each other. For example, you may want the user and administrative sections of a web application to have no access to each other, but undoubtedly you’ll have some shared resources that both sections need.

There are a number of interfaces that extend and classes that implement 

ApplicationContext

:

  • The 
    ConfigurableApplicationContext

    interface is, as the name implies, configurable, whereas the base 

    ApplicationContext

    is only readable.

  • The 
    org.springframework.web.context.WebApplicationContext

    and 

    ConfigurableWebApplicationContext

    interfaces are intended for Java EE web applications running in Servlet containers and provide access to the underlying 

    ServletContext

    and, if applicable, 

    ServletConfig

    .

  • The concrete classes 
    ClassPathXmlApplicationContext

    and 

    FileSystemXmlApplicationContext

    are designed to load the Spring configuration from XML files in a standalone application, whereas the 

    XmlWebApplicationContext

    achieves the same within Java EE web applications.

  • For programmatically configuring Spring using Java instead of XML, the 
    AnnotationConfigApplicationContext

    and 

    AnnotationConfigWebApplicationContext

    classes work in standalone and Java EE web applications, respectively.

In Java EE web applications, Spring handles web requests using a dispatcher Servlet, which delegates incoming requests to the appropriate controllers and translates request and response entities as needed. Your web application can have as many instances of the 

org.springframework.web.servlet.DispatcherServlet

class as makes sense for your use case.

Each 

DispatcherServlet

instance gets its own application context, which has references to the web application’s 

ServletContext

and its own 

ServletConfig

. You might create multiple 

DispatcherServlet

s, for example, to separate your web user interface from your web services. Because none of these 

DispatcherServlet

s can access the application context for any other 

DispatcherServlet

s, it is often desirable to share certain beans (such as business objects or data access objects) in a common root application context. This application context, global to the entire web application, is the parent of all the 

DispatcherServlet

s’ application contexts and is created using the 

org.springframework.web.context.ContextLoaderListener

. It, too, has a reference to the web application’s 

ServletContext

, but because it does not belong to any particular Servlet, it does not have a 

ServletConfig

reference.

Although the idea of having multiple 

DispatcherServlet

s is commonplace in web applications and is used throughout this book, it is only one configuration of infinite possibilities. In any standalone or web application, you can create whatever application context hierarchy your needs justify. As a general rule, you should always have one root application context from which all other application contexts inherit in one way or another, as shown in this figure.

One Root Application Context from which all other application contexts inherit

This article is excerpted from Wrox’s Professional Java for Web Applications (ISBN: 978-1-118-65646-4, copyright 2014 John Wiley & Sons) by Nicholas S. Williams. The remainder of chapter 12 goes on to work through boostrapping and configuring Spring Framework and using Bean Definition Profiles.

NICK WILLIAMS is a Software Engineer for UL Workplace Health and Safety in Franklin, Tennessee. A computer science graduate from Belmont University, he has been active in commercial and open source software projects for more than 9 years. He is the founder of DNSCrawler.com, a site for free DNS and IP troubleshooting tools, and NWTS Java Code, an open source community that specializes in obscure Java libraries that meet niche needs. In 2010, the Nashville Technology Council named him the Software Engineer of the Year for Middle Tennessee. Nick is a committer for Apache Logging (including Log4j) and Jackson Data Processor JSR 310 Data Types. He has also contributed new features to Apache Tomcat 8.0, Spring Framework 4.0, Spring Security 3.2, Spring Data Commons 1.6, Spring Data JPA 1.4, and JBoss Logging 3.2; serves as a contributor on several other projects, including OpenJDK; and is a member of the Java Community Process (JCP). You can find him on Twitter @Java_Nick.

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *