(Reprinted little assembly) Spring Framework Introduction

Author: Naveen Balani (naveenbalani@rediffmail.com), technical architect, Webify Solutions

In this three-part introduction to Spring framework of a series of articles in the first period, will begin to learn how to use Spring technology to build lightweight, robust J2EE applications. Regular developerWorks contributor Naveen Balani introduces the Spring Framework began his three-part of the Spring Series, which will introduce Spring aspect-oriented programming (AOP) and Inversion of Control (IOC) container.
Spring is an open source framework, is to address the complexity of enterprise application development created. One main advantage of the framework is its layered architecture, layered architecture allows you to choose which one component, and program development for the J2EE application to provide an integrated framework.

In this Spring by the three-part series Part 1, I will introduce the Spring framework. I first describe the framework of the perspective of the underlying model function of the framework, and then discuss the two most interesting modules: Spring aspect-oriented programming (AOP) and the inversion of control (IOC) container. Then a few examples demonstrate the use of IOC container in a typical application use case scenarios in the application. These examples will also be carried out later in the series expansion of a basis for discussion later in this article, will introduce the Spring framework constructed by Spring AOP way to achieve AOP.

Please refer to the download, Download Spring framework and Apache Ant, run the sample application in this series need them.

Spring Framework

Spring Framework is a hierarchical structure, well defined by the seven modules. Spring core container module built on top of the container defines the core to create, deploy and manage bean manner shown in Figure 1.

Figure 1. Spring Framework's seven modules
(Reprinted little assembly) Spring Framework Introduction

Spring framework composed of each module (or component) can stand alone, or with other joint realization of one or more modules. Each module functions as follows:

Core container: Spring core container provides the basic functions of the framework. The main components of the core container is the BeanFactory, it is the factory pattern. BeanFactory to use Inversion of Control (IOC) mode of the application's configuration and dependency specification and the actual separation of application code.
Spring context: Spring context is a configuration file, to the Spring Framework to provide context information. Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, validation and scheduling functions.
Spring AOP: through the configuration management features, Spring AOP module directly to the programming aspect-oriented features into the Spring framework. So, you can easily make any Spring managed object framework to support AOP. Spring AOP module for Spring applications based on the object to provide a transaction management service. Through the use of Spring AOP, EJB components do not rely on the declarative transaction management can be integrated into the application.
Spring DAO: JDBC DAO abstraction layer offers a meaningful exception hierarchy, the structure can be used to manage exception handling and different database vendors throw an error message. Exception hierarchy simplifies error handling, and greatly reduces The need to write exception code number (such as opening and closing the connection). Spring DAO JDBC-oriented exceptions comply with the generic DAO exception hierarchy.
Spring ORM: Spring Framework ORM framework into a number, which provides object-relational ORM tool, including JDO, Hibernate, and iBatis SQL Map. All comply with Spring's generic transaction and DAO exception hierarchy.
Spring Web module: Web context module built on top of the application context module, Web-based applications that provide a context. So, Spring framework supports integration with Jakarta Struts. Web module also streamlined the processing of multi-part request and the request parameters bound to domain objects work.
Spring MVC framework: MVC framework for building a fully functional Web application MVC implementation. Through strategy interfaces, MVC framework into a highly configurable, MVC view to accommodate a large number of technologies, including JSP, Velocity, Tiles, iText, and POI.

Spring Framework features can be used in any J2EE server, most of the functionality also applies to the unregulated environment. Spring's core point is: do not bind to a specific J2EE support services for reusable business and data access objects. There is no doubt that such objects can be in different J2EE environments (Web or EJB), standalone applications, test environments reuse.


Inversion of Control pattern (also known as dependency intervention) the basic concept is: do not create objects, but create them in the way described. In the code is not directly connected with the objects and services, but in the configuration file which describes what a component needs a service. Container (in the Spring framework is the IOC container) is responsible for these together.

In a typical IOC scenario, the container creates all objects, and set the necessary properties to connect them together, decide what time to call the method. The following table lists the IOC of an implementation model.

Type 1 service needs to implement a special interface, through the interface from the object to provide these services, you can query from the object-dependent (for example, require additional services)
Type 2 through JavaBean properties (such setter method) 3-dependent distribution of dependent type to the form constructor, not in the form of public JavaBean properties

Spring Framework's IOC container with type 2 and type 3 implementation.

Aspect-oriented programming

Aspect-oriented programming, that is, AOP, is a programming technology that allows programmers to crosscutting concerns or cross-cutting behavior of the typical duties of the line (such as logging and transaction management) module. AOP's core structure is concerned, it will affect the number of classes that encapsulate the behavior of reusable modules.

AOP and IOC are complementary technologies, they all use a modular solution to enterprise application development in the complex. In a typical object-oriented development methods, you may want to log all statements on the Java class methods and logging can be achieved. In the AOP approach, you can turn the log service module, and to declare the way they are applied to the components need to log on. Of course, the advantage is the Java class does not need to know the existence of the log service does not need to consider the relevant code. Therefore, applications written using Spring AOP is loosely coupled code.

AOP functionality is fully integrated into the Spring transaction management, logging and other features of context.

IOC Container

Spring design is the org.springframework.beans package, it's designed to be used together with JavaBean components. This package is usually not used directly by the user, but by the server to function as the bottom of most other intermediary. Abstract is the next most senior BeanFactory interface, it is the realization of the factory design pattern that allows to create and retrieve objects by name. BeanFactory can also manage the relationship between objects.

BeanFactory supports two object model.

Single-state model provides the name of the object with a specific instance of sharing, when it can be retrieved in the query. Singleton is the default and most common object model. For the non-state requirements are very good.
Prototype model to ensure that each search will create a separate object. In each user needs its own object, the prototype model of the best.
Spring bean factory concept is the basis for IOC container. IOC will be the responsibility of dealing with things from the application code is transferred to the frame. As I will be next, as shown in the example, Spring framework uses JavaBean properties and configuration data that must be set dependencies.

BeanFactory Interface

Because org.springframework.beans.factory.BeanFactory is a simple interface, so you can achieve for a variety of underlying storage methods. The most commonly used BeanFactory definition XmlBeanFactory, it is defined according to XML file into bean, as shown in Listing 1.

Listing 1. XmlBeanFactory
BeanFactory factory = new XMLBeanFactory (new FileInputSteam ("mybean.xml"));

Defined in the XML file loaded Bean was negative, which means you need before bean, bean itself will not be initialized. Retrieved from the BeanFactory bean, simply call the getBean () method, introduced bean to be the name can be retrieved, as shown in Listing 2.

Listing 2. GetBean ()
MyBean mybean = (MyBean) factory.getBean ("mybean");

Each bean definition can be a POJO (JavaBean initialization with the class name and attributes defined) or FactoryBean. FactoryBean interface using Spring framework for building applications that add an indirect level.

IOC example

Understanding Inversion of control is the easiest way to see the practical application of it. In the three-part series, Part 1 Spring summarize, I use an example, demonstrates how Spring IOC container into the application's dependencies (rather than build them come in).

I used to open credit accounts online use cases as a starting point. For the realization of open credit account requires the user to interact with the following services:

Credit rating assessment services, check the user's credit history information.
Links to remote information services into customer information, customer information and credit card and bank information to connect to the automatic debit (if needed).
E-mail service to send e-mail credit card status.

3 Interface

For this example, I assume that the service already exists, the ideal situation is to use loosely coupled way to integrate them. The following list shows the three services of the application program interface.

Listing 3. CreditRatingInterface
public interface CreditRatingInterface (
public boolean getUserCreditHistoryInformation (ICustomer iCustomer);

Listing 3 shows the credit rating assessment interface provides credit history information. It requires a Customer object that contains customer information. The interface implementation is provided by the CreditRating class.

Listing 4. CreditLinkingInterface
public interface CreditLinkingInterface (
public String getUrl ();
public void setUrl (String url);
public void linkCreditBankAccount () throws Exception;

Link interface credit history credit information and bank information (if required) to connect together, and insert the user's credit card information. Credit Link interface is a remote service, it queries through getUrl () method of. URL from the Spring bean configuration mechanism to set the framework, I will discuss it. The interface implementation is provided by the CreditLinking class.

Listing 5. EmailInterface
public interface EmailInterface (
public void sendEmail (ICustomer iCustomer);
public String getFromEmail ();
public void setFromEmail (String fromEmail);
public String getPassword ();
public void setPassword (String password);
public String getSmtpHost ();
public void setSmtpHost (String smtpHost);
public String getUserId ();
public void setUserId (String userId);

EmailInterface charge to customers on credit card status send an e-mail. E-mail configuration parameters (such as SMPT host, user name, password) from the previously mentioned mechanism of bean configuration settings. Email class provides the interface.

Spring to keep it loose

These interfaces in place, the next thing to consider is how to integrate them together loosely coupled way. In Listing 6 you can see the realization of use cases of credit card accounts.

Listing 6:
public class CreateCreditCardAccount implements
CreateCreditCardAccountInterface (

public CreditLinkingInterface getCreditLinkingInterface () (
return creditLinkingInterface;

public void setCreditLinkingInterface (
CreditLinkingInterface creditLinkingInterface) (
this.creditLinkingInterface = creditLinkingInterface;

public CreditRatingInterface getCreditRatingInterface () (
return creditRatingInterface;

public void setCreditRatingInterface (CreditRatingInterface creditRatingInterface)
this.creditRatingInterface = creditRatingInterface;

public EmailInterface getEmailInterface () (
return emailInterface;

public void setEmailInterface (EmailInterface emailInterface) (
this.emailInterface = emailInterface;

/ / Client will call this method
public void createCreditCardAccount (ICustomer icustomer) throws Exception (
boolean crediRating =
getCreditRatingInterface (). getUserCreditHistoryInformation (icustomer);
icustomer.setCreditRating (crediRating);
/ / Good Rating
if (crediRating) (
getCreditLinkingInterface (). linkCreditBankAccount (icustomer);

getEmailInterface (). sendEmail (icustomer);


Note that all the setter methods are implemented Spring bean configuration. All the dependencies (that is, three interface) by the Spring framework can be injected with these bean. createCreditCardAccount () method will be used to perform the remaining services to achieve. You can see in Listing 7 Spring configuration file. I use the arrows to highlight these definitions.

Listing 7:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "- / / SPRING / / DTD BEAN / / EN"

<bean --> define createCreditCard definition
class = "springexample.creditcardaccount.CreateCreditCardAccount">
<property name="creditRatingInterface"> -> inject creditRatingInterface dependency via creditRating reference bean
<ref bean="creditRating" />
</ Property>
<property name="creditLinkingInterface"> ">--> inject creditLinkingInterface dependency via creditLinking reference bean
<ref bean="creditLinking" />
</ Property>
<property name="emailInterface"> ">">--> inject emailInterface dependency via email reference bean
<ref bean="email" />
/ Property>
</ Bean>

<property name="url">
<value> http://localhost/creditLinkService </ value> -> set url property value
</ Property>
</ Bean>

</ Bean>

<property name="smtpHost">
<value> localhost </ value >>--> set smpHtpHost property value
</ Property>
<property name="fromEmail">
<value> mycompanyadmin@mycompanyadmin.com </ value>
</ Property>
<property name="userId">
<value> myuserid </ value>
</ Property>
<property name="password">
<value> mypassword </ value>
</ Property>
</ Bean>
</ Beans>

Run the application

To run the sample application, you must first download the Spring Framework and all its dependent files. Next, will be released into the framework (for example) disk c: \, it will create C: \ spring-framework-1.2-rc2 (applicable to the current release version) this folder. Before continuing operation of the back must also download and released Apache Ant.

Next, release the source code to the folder, for example c: \ drive, then create SpringProject. The Spring library (ie C: \ spring-framework-1.2-rc2 \ dist under spring.jar and C: \ spring-framework-1.2-rc2 \ lib \ jakarta-commons under the commons-logging.jar) copy to SpringProject \ lib folder. After completion of these tasks, there is the necessary build dependencies set.

Open a command prompt, switch to the current directory SpringProject, at the command prompt, type the following command: build.

This will build and run the CreateCreditAccountClient class, the class will create the Customer class object to run and fill it, will call CreateCreditCardAccount class to create and link a credit card account. CreateCreditAccountClient also by ClassPathXmlApplicationContext into Spring configuration file. Into bean, you can by getBean () method to access them, and as shown in Listing 8.

Listing 8. Into Spring configuration file
ClassPathXmlApplicationContext appContext =
new ClassPathXmlApplicationContext (new String [] (
CreateCreditCardAccountInterface creditCardAccount =
appContext.getBean ("createCreditCard");


In this Spring from the three-part series of the first article, I introduced the Spring framework. I discuss the hierarchical structure of the composition of Spring's seven modules beginning, and insight into the two modules: Spring AOP and IOC container.

As the best way to learn is practice, so I introduced with a working example of IOC mode (like Spring's IOC container to achieve it) the way how loosely coupled distributed system integrated. In this example, you can see, the dependence of the work or service into the credit card account application, than build them from scratch is much easier.

Please continue to follow this series for the next article, I will be here to learn the knowledge, the paper introduces Spring AOP module How in the enterprise applications to provide sustained support and allow you to begin to understand Spring MVC Mokuai and Xiangguanchajian.

分类:Java 时间:2010-06-01 人气:399
blog comments powered by Disqus


  • Spring refresher (f) AOP Aspect Oriented Programming <2> 2011-04-19

    The previous chapter we talked about using proxy mode to automatically manage ISpeaker interfaces in the say () method automatically in say () method before and after the addition we get / give gifts methods. But a more comprehensive idea of students

  • Aspect Oriented Programming AOP 2010-04-28

    Reprinted: http://wayfarer.cnblogs.com/articles/241024.html The birth of AOP technology is not late, as early as 1990, from the Xerox Palo Alto Research Lab (or PARC) researchers in object-oriented thinking on the limitations of the analysis. They de

  • AOP (Aspect oriented programming) aspect-oriented programming 2010-09-29

    An AOP (Aspect oriented programming) aspect-oriented programming OOP Object-oriented programming AOP Although the literal and very similar to OOP , But it is for the two different areas of design. OOP is a process-oriented programming method based on

  • Spring Aspect Oriented Programming 2015-04-02

    本文是一篇Spring AOP的基础知识分析文章,其中不牵扯源码分析,只包含AOP中重要概念的讲解,分析,以及Spring AOP的用法. Spring 从2.0版本引入了更加简单却强大的基于xml和AspectJ注解的面向切面的编程方式.在深入了解如何用Spring 进行面向切面的编程前,我们先了解AOP中的几个重要的基本概念,这几个概念并非Spring特有的,并且从字面上看有些难于理解,不过我会尽量用实例和通俗的语言来进行阐述. 首先,到底什么是AOP呢,它有什么用处呢,对我们程序员有什么好

  • Aspect Oriented Programming spring 2010-12-27

    @ Aspect public class AspectCoupon implements Ordered { @ AfterReturning (pointcut = "execution (public * com.longtuo.server.bo.www.CustomerInfoService.saveCustomerInfo (..))", returning =" user ") public void sentRegisterCoupon (Users

  • AOP aspect oriented programming 2010-08-19

    Spring, the introduction of the CGLib as no interface in case of dynamic proxy implementation. CGLib with Dynamic Proxy proxy mechanism essentially similar, but the dynamically generated proxy object is not an interface implementation, but the target

  • Principles and Spring AOP interceptor 2010-10-26

    Principle AOP (Aspect Oriented Programming), that is, aspect-oriented programming techniques. IoC AOP-based foundation, is a useful complement to OOP. AOP will apply the system is divided into two parts, the core business logic (Core business concern

  • Summary of Spring AOP 2010-09-29

    Spring In conclusion AOP AOP(Aspect Oriented Programming) Aspect-oriented programming, in short, to achieve cross-section (crossing) Tool. In many parts of a program re-use of a piece of logic that we can be pulled out as an aspect , Reconstruction a

  • Understanding of the concept of Spring AOP [change] 2010-07-03

    1. I know aop At first glance aop, up is a lot of terminology , But also a pull-style name, Aspect Oriented Programming , Say this is a useful complement to OOP, etc. . Once you know what to do, thinking : No wonder many people and I said, more diffi

  • Spring AOP reference manual 2010-09-29

    Spring AOP reference manual Overview Spring 2.0 Introduces a simple but powerful mechanism-based models and @AspectJ Note implement custom aspects of the style. Spring currently supports only method execution join point does not support field interce

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.644 (s). 12 q(s)