Introduction to Spring framework

Source: Internet
Author: User
Tags db2 to domain

Spring AOP and IOC containers

Document options

<Tr valign = "TOP"> <TD width = "8"> </TD> <TD width = "16"> </ TD> <TD class = "small" width = "122"> <p> <SPAN class = "Ast"> the required JavaScript document options are not displayed </span> </P> </TD> </tr>


Send this page as an email

Sample Code


Level: elementary

Naveen balani, technical architect, webify Solutions

August 18, 2005

In the first phase of this three-part Spring framework series, we will begin to learn how to use spring technology to build lightweight and robust J2EE applications. By introducing the Spring framework, Naveen balani, a regular contributor to developerworksSpring SeriesSpring's Aspect-oriented programming (AOP) and control inversion (IOC) containers will also be introduced.

Spring is an open-source framework created to solve the complexity of enterprise application development. One of the main advantages of the Framework is its layered architecture, which allows you to choose which component to use and provides an integrated framework for J2EE application development.

This article consists of three parts:Spring SeriesIn section 1st, I will introduce the Spring framework. I will first describe the functions of the framework from the perspective of the underlying model of the framework, and then discuss two of the most interesting modules: Spring Aspect-oriented programming (AOP) and control inversion (IOC) containers. Next, we will use several examples to demonstrate the application of IOC containers in typical application case scenarios. These examples will also be the basis for the expansion discussion in the later sections of this series. In the later sections of this article, we will introduce how the Spring framework implements the AOP construction through Spring AOP.

See download and download the Spring framework and Apache ant. They are required to run sample applications in this series.

Spring framework

The Spring framework is a layered architecture consisting of seven well-defined modules. The spring module is built on the core container. The core container defines how to create, configure, and manage beans, as shown in figure 1.

Figure 1. Seven modules of the Spring framework

Each module (or component) that makes up the Spring framework can exist independently or be implemented together with one or more modules. The functions of each module are as follows:

  • Core container: The Core container provides the basic functions of the Spring framework. The main component of the core container isBeanFactoryIt is the implementation of the factory model.BeanFactoryUseControl reversal(IOC) mode separates application configuration and dependency specifications from actual application code.
  • Spring Context: Spring context is a configuration file that provides context information to the Spring framework. Spring context includes enterprise services, such as JNDI, EJB, email, internationalization, checksum and scheduling.
  • Spring AOP: Through the configuration management feature, the Spring AOP module directly integrates Aspect-oriented programming functions into the spring framework. Therefore, any objects managed by the Spring framework can easily support AOP. The Spring AOP module provides transaction management services for objects in spring-based applications. By using Spring AOP, You can integrate declarative transaction management into applications without relying on EJB components.
  • Spring Dao: The JDBC Dao abstraction layer provides a meaningful exception hierarchy for managing Exception Handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of Exception Code to be written (for example, opening and closing connections ). JDBC-oriented exceptions of spring Dao follow the common Dao exception hierarchy.
  • Spring ORM: The Spring framework inserts several ORM frameworks to provide ORM Object Relational tools, including JDO, hibernate, and ibatis SQL map. All of these comply with the general transactions and Dao exception hierarchies of spring.
  • Spring web module: The Web context module is built on the application context module, providing context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The web module also simplifies processing multiple requests and Binding Request Parameters to domain objects.
  • Spring MVC Framework: The MVC Framework is a full-featured MVC implementation for Building Web applications. Through the policy interface, the MVC framework becomes highly configurable. MVC supports a large number of view technologies, including JSP, velocity, tiles, itext, and poi.

The functions of the Spring framework can be used on any J2EE server. Most of the functions are also applicable to unmanaged environments. Spring supports reusable services and data access objects that are not bound to a specific J2EE service. There is no doubt that such objects can be reused between different J2EE environments (web or EJB), independent applications, and test environments.



Back to Top

IOC and AOP

The basic concept of the inversion mode (also known as dependency intervention) is to describe how to create objects without creating them. The Code does not directly connect to objects and services, but describes which component needs which service in the configuration file. Containers (IOC containers in the Spring framework) are responsible for connecting these together.

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

Type 1 Services need to implement special interfaces through which objects provide these services and can query Dependencies from objects (for example, additional services required)
Type 2 Allocate Dependencies by using JavaBean attributes (such as the setter method)
Type 3 Dependencies are provided in the form of constructor and not published in the form of JavaBean attributes.

The IOC container of the Spring framework is implemented by Type 2 and Type 3.

Aspect-Oriented Programming

Aspect-Oriented Programming(AOP) is a programming technology that allows programmers to modularize cross-concern or cross-responsibility line behavior (such as logging and transaction management. The core structure of AOP isAspectIt encapsulates actions that affect multiple classes into reusable modules.

AOP and IOC are complementary technologies that use modular methods to solve complex problems in enterprise application development. In a typical object-oriented development method, you may need to place the logging statement in all methods and Java classes to implement the logging function. In the AOP method, the log ServiceModular, And apply them to the components that require logs in a declarative manner. Of course, the advantage is that the Java class does not need to know the existence of the log service or consider the relevant code. Therefore, application code written with Spring AOP is loosely coupled.

The functions of AOP are fully integrated into the context of Spring transaction management, logs, and other features.



Back to Top

IOC container

The core of spring design isorg.springframework.beansPackage, which is designed to be used together with the JavaBean Component. This package is usually not directly used by users, but is used by the server as the underlying intermediary for most other functions. The next highest level abstraction isBeanFactoryInterface, which is the implementation of the factory design mode and allows the creation and retrieval of objects by name.BeanFactoryYou can also manage relationships between objects.

BeanFactoryTwo object models are supported.

  • Single StateThe model provides shared instances of objects with specific names, which can be searched during queries. Singleton is the default and most commonly used object model. It is ideal for stateless service objects.
  • PrototypeMake sure that a separate object is created for each search. When each user needs their own objects, the prototype model is the most suitable.

The concept of Bean Factory is that spring serves as the basis of IOC containers. IOC transfers the responsibility for handling tasks from application code to the framework. As I will demonstrate in the next example, the Spring framework uses the JavaBean attribute and configuration data to indicate the dependencies that must be set.

Beanfactory Interface

Becauseorg.springframework.beans.factory.BeanFactoryIs a simple interface, so it can be implemented for various underlying storage methods. The most commonBeanFactoryDefinition isXmlBeanFactoryIt loads beans according to the definition in the XML file, as shown in Listing 1.

Listing 1. xmlbeanfactory

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

The bean defined in the XML file is passively loaded, which means that the bean itself will not be initialized before the bean is needed. ToBeanFactoryTo retrieve beans, you only need to callgetBean()Method. enter the name of the bean to be retrieved, as shown in Listing 2.

Listing 2. getbean ()

MyBean mybean = (MyBean) factory.getBean("mybean");

The definition of each bean can be pojo (Class Name and JavaBean initialization attribute definition) orFactoryBean.FactoryBeanThe interface adds an indirect level to the application built using the Spring framework.



Back to Top

IOC example

The simplest way to understand control reversal is to look at its practical application. InSpring SeriesI used an example to demonstrate how to inject application dependencies through the Spring IoC container (instead of building them in ).

I started with an online credit account use case. To enable a credit account, you must interact with the following services:

  • The credit level evaluation service queries users' credit history information.
  • Connect the remote information service, insert the customer information, and connect the customer information with the credit card and bank information for automatic debit (if needed ).
  • The email service sends an email about the credit card status to the user.



Back to Top

Three Interfaces

For this example, I assume that the service already exists. Ideally, they are integrated in a loosely coupled manner. The following list shows the application interfaces of the three services.

Listing 3. creditratinginterface

public interface CreditRatingInterface {
public boolean getUserCreditHistoryInformation(ICustomer iCustomer);
}

The credit level evaluation interface shown in listing 3 provides credit history information. It requiresCustomerObject. This interface is implementedCreditRatingClass.

Listing 4. creditlinkinginterface

public interface CreditLinkingInterface {
public String getUrl();
public void setUrl(String url);
public void linkCreditBankAccount() throws Exception ;
}

The credit Link interface connects the credit history information with the bank information (if needed) and inserts the user's credit card information. The credit Link interface is a remote service.getUrl()Method. The URL is set by the bean configuration mechanism of the Spring framework. I will discuss it later. This interface is implementedCreditLinkingClass.

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);
}

EmailInterfaceSends emails about the customer's credit card status to the customer. The mail configuration parameters (such as smpt host, user name, and password) are set by the bean configuration mechanism mentioned above.EmailClass provides the implementation of this interface.



Back to Top

Spring makes it loose

After these interfaces are in place, the next thing to consider is how to integrate them in a loosely coupled manner. In Listing 6, you can see the implementation of the credit card account use case.

Note that all setter methods are implemented by spring configuration bean. All dependencies (that is, three interfaces) can be injected by the Spring framework using these beans.createCreditCardAccount()The method will use the service to execute other implementations. You can see the spring configuration file in listing 7. I highlighted these definitions with arrows.



Back to Top

Run the application

To run the sample application, you must first download the Spring framework and all its dependent files. Next, release the framework to (for example) a disk.C :/This createsC:/spring-framework-1.2-rc2(Applicable to the current release version. Before proceeding to the subsequent operations, you must download and release Apache ant.

Next, release the source code to a folder, suchC :/Disk, and then createSpringproject. Set the spring Library (that isC:/spring-framework-1.2-rc2/DistUnderSpring. JarAndC:/spring-framework-1.2-rc2/lib/Jakarta-commonsUnderCommons-logging.jar) CopySpringproject/libFolder. After completing these tasks, you must build a dependency set.

Open a command prompt and switch the current directorySpringprojectIn the command prompt, enter the following command:build.

This will build and runCreateCreditAccountClientClass.CustomerClass Object and fill it in, it will also callCreateCreditCardAccountClass to create and link a credit card account.CreateCreditAccountClientWill also passClassPathXmlApplicationContextLoad the spring configuration file. After loading the bean, you can usegetBean()Method, as shown in listing 8.

Listing 8. Load the spring configuration file

ClassPathXmlApplicationContext appContext = 
new ClassPathXmlApplicationContext(new String[] {
"springexample-creditaccount.xml"
});
CreateCreditCardAccountInterface creditCardAccount =
(CreateCreditCardAccountInterface)
appContext.getBean("createCreditCard");


Back to Top

Conclusion

This article consists of three parts:Spring SeriesIn the first article, I introduced the basics of the Spring framework. I started from discussing the seven modules that made up the spring layered architecture, and then introduced two modules: Spring AOP and IOC containers.

The best method for learning is practice, so I used a working example to introduce the IOC mode (as implemented by the Spring IoC container) how to integrate distributed systems in a loosely coupled manner. In this example, it is much easier to inject dependencies or services into credit card account applications at work than to create them from the beginning.

Please continue to pay attention to this series of next articles. I will introduce how the Spring AOP module provides persistent support in enterprise applications based on my knowledge here, and let you get started with the spring MVC module and related plug-ins.



Back to Top

Download

Description Name Size Download Method
Examples: source code, spring files, build scripts Wa-spring1-SpringProject.zip 9 KB HTTP
Information about the Download Method

References

  • For more information, see the original article on the developerworks global site.

  • Although Spring AOP provides unique advantages, it is not the only AOP implementation. See "AOP @ work: Comparison of AOP tools, Part 1 "(DeveloperworksFebruary 2005). Learn about the composition of Spring AOP.
  • Through "object relationship ing without containers "(DeveloperworksApril 2004) learned how to use Hibernate and Spring AOP to develop a transactional persistent layer ).
  • Download the Spring framework from spring homepage.
  • Download Apache ant from ANT homepage.
  • Join the developerworks community by joining developerworks blogs.
  • SeeDeveloperworksSome of the following references:
    • The articles in the Web architecture area specifically introduce various web-based solutions.
    • Developer Bookstore provides a complete list of technical books, including hundreds of books on web-related topics.

About the author

 

Naveen balani spent most of his time designing and developing J2EE-based frameworks and products. He is an IBMDeveloperworksI have written various articles on ESB, SOA, JMS, WebServices ubuntures, CICs, axis, DB2 XML extender, WebSphere Studio, MQSeries, and Java wireless devices, DB2 everyplace for Palm, j2-midp, Java-Nokia, Visual Studio.. NET and wireless data synchronization. You can contact him via naveenbalani@rediffmail.com.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.