Author: Naveen Balani (firstname.lastname@example.org), 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 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
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.
IOC and AOP
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, 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.
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.
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.
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.
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.
public class CreateCreditCardAccount implements
public CreditLinkingInterface getCreditLinkingInterface () (
public void setCreditLinkingInterface (
CreditLinkingInterface creditLinkingInterface) (
this.creditLinkingInterface = creditLinkingInterface;
public CreditRatingInterface getCreditRatingInterface () (
public void setCreditRatingInterface (CreditRatingInterface creditRatingInterface)
this.creditRatingInterface = creditRatingInterface;
public EmailInterface getEmailInterface () (
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);
/ / 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.
<? 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 name="creditLinkingInterface"> ">--> inject creditLinkingInterface dependency via creditLinking reference bean
<ref bean="creditLinking" />
<property name="emailInterface"> ">">--> inject emailInterface dependency via email reference bean
<ref bean="email" />
<value> http://localhost/creditLinkService </ value> -> set url property value
<value> localhost </ value >>--> set smpHtpHost property value
<value> email@example.com </ value>
<value> myuserid </ value>
<value> mypassword </ value>
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 =
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.
Related Posts of (Reprinted little assembly) Spring Framework Introduction
Following the vicinity of the DWR framework for Ajax are examples of entry, welcome to download ...............
Series, the previous article said that Ruby on Rails is a sudden pop up a framework for the Ruby programming language to serve as a catalyst. With the continued success of the experience of Ruby, developers began to seek their Ruby applications and u ...
What is a software architect? Architect (Architecture) a lot of software companies are currently the most urgent need of talent, but also a software enterprise in the highest salaries of technical personnel. In other words, the architect is the human ...
1, how to study Spring? You can study through the following means spring: (1) spring package download doc directory under MVC-step-by-step and the sample directory are relatively good examples of spring development examples. (2) AppFuse integrates a numbe
Excerpt from: http://blog.csdn.net/exceljava/archive/2007/10/05/1811925.aspx Download the spring package of documents and a variety of packages large projects are often at only some of which we must, if not sure what package when necessary, then take a lo
AspectJ directory are in the Spring framework to use AspectJ source code and test program files. AspectJ is the first java application framework provided by the AOP. dist directory is a Spring release package, regarding release package described below in
Although the workflow is still immature stage of development, not even a recognized standard. But its application has already been launched in the Express, indicating the market's demand for job-flow framework are urgent and enormous. Backgrounds of o
applicationContext.xml file content <? xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = " http://www.springframework.org/schema/beans " xmlns: xsi = " http://www.w3.org/2001/XMLSchema-instance " ...
First, Appfuse brief introduction Matt Raible are Appfuse developed a guiding entry-level J2EE framework, how to integrate its popular Spring, Hibernate, ibatis, struts, Xdcolet, junit, etc. give the basic framework of the model, the latest version 1.7 is
applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com