Learning to use spring and SPRINGMVC for a while, but did not properly tidy up the spring information, today, especially in the online review, by the way to collate the relevant information.
Spring Series: Introduction to Spring Framework
Getting Started with Spring AOP and IOC containers
In the first installment of this three-part series that introduces the spring framework, you will begin to learn how to build lightweight, robust Java EE applications with spring technology. DeveloperWorks's regular contributor, Naveen Balani, begins his three-part Spring Series by introducing the spring framework, which also introduces spring aspect-oriented programming (AOP) and control inversion (IOC) containers.
Spring is an open source framework that is created to address the complexities of enterprise application development. One of the main advantages of the framework is its layered architecture, which allows you to choose which components to use while providing an integrated framework for Java EE application development.
In the 1th part of this three-part Spring Series , I'll cover the spring framework. I first describe the framework's functionality from the perspective of the framework's underlying model, and then we'll discuss the two most interesting modules: Spring aspect-oriented programming (AOP) and control inversion (IOC) containers. A few examples are then used to demonstrate the application of the IOC container in a typical application use case scenario. These examples will also serve as the basis for an expanded discussion later in this series, which will explain how the spring framework implements AOP constructs through Spring AOP later in this article.
See download, download Spring framework and Apache Ant, which are required to run the sample application for this series.
Spring Framework
The Spring framework is a layered architecture consisting of 7 well-defined modules. The Spring modules are built on top of the core container, and the core container defines how the beans are created, configured, and managed, as shown in 1.
Figure 1. 7 Modules of the Spring framework
Each module (or component) that makes up the Spring framework can exist separately or be implemented in conjunction with one or more other modules. The functions of each module are as follows:
- Core Container : The core container provides the basic functionality of the Spring framework. The main component of the core container is
BeanFactory
that it is the implementation of the factory pattern. BeanFactory
Use the inversion of Control (IOC) pattern to separate the application's configuration and dependency specifications from the actual application code.
- Spring Context : The spring context is a configuration file that provides contextual information to the spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, checksum scheduling.
- Spring AOP: With the configuration management feature, the Spring AOP module directly integrates aspect-oriented programming capabilities into the spring framework. Therefore, it is easy to enable any object managed by the Spring framework to 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 your application without relying on EJB components.
- Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of exception codes that need to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exception conforms to the common DAO exception hierarchy.
- Spring ORM: The Spring Framework inserts several ORM frameworks, providing ORM object-relational tools, including JDO, Hibernate, and IBatis SQL Map. All of these conform to Spring's common transaction and DAO exception hierarchies.
- Spring Web Module : The Web context module is built on top of the application context module and provides the context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the process of working with multipart requests and binding request parameters to domain objects.
- Spring MVC Framework : The MVC framework is a full-featured MVC implementation of building WEB applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, IText, and POI.
The functionality of the Spring framework can be used in any Java EE server, and most features are also available in an out-of-management environment. The core point of Spring is to support reusable business and data access objects that are not tied to a particular Java EE service. There is no doubt that such objects can be reused across different Java EE environments (Web or EJB), standalone applications, and test environments.
IOC and AOP
The basic concept of control reversal mode (also known as dependency intervention) is that you do not create objects, but describe how they are created. The code does not directly connect to objects and services, but describes in the configuration file which component requires which service. Containers (which are IOC containers in the Spring framework) are responsible for linking these together.
In a typical IOC scenario, the container creates all the objects and sets the necessary properties to connect them together, deciding when to invoke the method. The following table lists an implementation pattern for the IOC.
Type 1 |
services need to implement specialized interfaces through interfaces that provide these services from objects, and can query dependencies from objects (for example, additional services needed) |
Type 2 |
Assigning dependencies through JavaBean properties, such as setter methods |
Type 3 |
Dependencies are provided as constructors and are not exposed as JavaBean properties |
The IOC container for the Spring framework is implemented with type 2 and type 3.
Aspect-oriented programming
aspect-oriented programming , AOP, is a programming technique that allows programmers to modularize the behavior of crosscutting concerns or crosscutting typical lines of responsibility, such as logging and transaction management. The core structure of AOP is the facet , which encapsulates behaviors that affect multiple classes into reusable modules.
AOP and IOC are complementary technologies that use a modular approach to solve complex problems in enterprise application development. In a typical object-oriented development approach, logging statements may be placed in all methods and Java classes in order to implement logging functionality. In the AOP approach, the log service can be modularized in turn and applied declaratively to the component that needs the log. Of course, the advantage is that the Java class does not need to know the existence of the log service and does not need to consider the associated code. Therefore, application code written in Spring AOP is loosely coupled.
The functionality of AOP is fully integrated into the context of Spring transaction management, logging, and various other features.
IOC container
The core of Spring design is the org.springframework.beans
package, which is designed to be used with the JavaBean component. This package is not usually used directly by the user, but is used by the server as the underlying intermediary for most other functions. The next highest-level abstraction is the BeanFactory
interface, which is the implementation of the factory design pattern, allowing objects to be created and retrieved by name. BeanFactory
You can also manage the relationships between objects.
BeanFactory
Supports two object models.
- A single-state model provides a shared instance of an object with a specific name that can be retrieved at query time. Singleton is the default and most commonly used object model. Ideal for stateless service objects.
- The prototype model ensures that each retrieval creates a separate object. The prototype model works best when each user needs his or her own object.
The Bean Factory concept is the basis of Spring as an IOC container. The IOC shifts responsibility for handling things from application code to frameworks. As I will demonstrate in the next example, the Spring framework uses the JavaBean property and configuration data to indicate the dependencies that must be set.
Beanfactory interface
Because org.springframework.beans.factory.BeanFactory
it is a simple interface, it can be implemented for a variety of underlying storage methods. The most common BeanFactory
definition is XmlBeanFactory
that it loads the bean 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 beans defined in the XML file are negatively loaded, which means that the bean itself will not be initialized until the bean is needed. To BeanFactory
retrieve a bean, simply call the getBean()
method and pass in the name of the bean that will be retrieved, as shown in Listing 2.
Listing 2. Getbean ()
Mybean Mybean = (Mybean) factory.getbean ("Mybean");
Each bean's definition can be POJO (with the class name and JavaBean initialization property definition) or FactoryBean
. FactoryBean
interface adds an indirect level to an application built using the Spring framework.
IOC Example
The simplest way to understand control inversion is to look at its practical application. In summarizing the 1th part of the Spring Series , which consists of three parts, I used an example that showed how to inject the application's dependencies through the Spring IOC container (rather than building them in).
I use the use case as a starting point for opening an online credit account. For this implementation, opening a credit account requires the user to interact with the following services:
- Credit rating service, which queries the user's credit history information.
- Remote information linking service, inserting customer information, connecting customer information to credit card and bank information for automatic debit (if necessary).
- e-mail Service to send users an email about the status of the credit card.
Three interfaces
For this example, I assume that the service already exists, and ideally the situation is to integrate them in a loosely coupled fashion. The following list shows the application interfaces for three services.
Listing 3. Creditratinginterface
Public interface Creditratinginterface {public boolean getusercredithistoryinformation (Icustomer icustomer);}
The credit rating interface shown in Listing 3 provides credit history information. It requires an object that contains customer information Customer
. The implementation of this interface is CreditRating
provided by the class.
Listing 4. Creditlinkinginterface
Public interface Creditlinkinginterface {public String getUrl ();p ublic void seturl (String url);p ublic void Linkcreditbankaccount () throws Exception;}
The credit link interface connects the credit history information with the bank information (if necessary) and inserts the user's credit card information. The credit link interface is a remote service, and its query is getUrl()
done by means of a method. The URL is set by the Spring framework's bean configuration mechanism, which I'll discuss later. The implementation of this interface is CreditLinking
provided by the 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
Responsible for sending emails to customers about the status of the customer's credit card. The message configuration parameters (such as the SMPT host, user name, password) are set by the bean configuration mechanism mentioned earlier. Email
class provides an implementation of this interface.
Spring keeps it loose
After these interfaces are in place, the next thing to consider is how to integrate them in a loosely coupled fashion. You can see the implementation of the credit card account use case in Listing 6.
Note that all setter methods are implemented by Spring's configuration bean. All dependencies (that is, three interfaces) can be injected by the Spring framework with these beans. createCreditCardAccount()
method uses the service to perform the rest of the implementation. You can see the Spring configuration file in Listing 7. I use arrows to highlight these definitions.
Running the application
To run the sample application, you must first download the Spring framework and all of its dependent files. Next, release the framework to (for example) disk \ c, which creates a folder such as C:\spring-framework-1.2-rc2 (for the current release). You must also download and release Apache Ant before proceeding with the following operations.
Next, release the source code to the folder, such as the C: \ disk, and then create the springproject. The Spring library ( Spring.jar and C:\spring-framework-1.2-rc2\lib\ under the C:\spring-framework-1.2-rc2\dist Jakarta-commons Commons-logging.jar) is copied to the springproject\lib folder. Once you have completed these tasks, you have the necessary build dependency set.
Open a command prompt, switch the current directory to Springproject, and enter the following command at a command prompt: build
.
This builds and runs the class CreateCreditAccountClient
, which creates the Customer
class object and populates it, and invokes the class to CreateCreditCardAccount
create and link the credit card account. CreateCreditAccountClient
It also ClassPathXmlApplicationContext
loads the Spring configuration file. After the beans have been loaded, they can be getBean()
accessed through methods, as shown in Listing 8.
Listing 8. Loading the Spring configuration file
Classpathxmlapplicationcontext AppContext = new Classpathxmlapplicationcontext (new string[] { " Springexample-creditaccount.xml " }); Createcreditcardaccountinterface CreditCardAccount = (createcreditcardaccountinterface) AppContext.getBean (" Createcreditcard ");
Conclusion
In the first article in this three-part Spring Series , I introduced the basics of the spring framework. I started with a discussion of the 7 modules that make up the spring hierarchy, and then I covered two of them: Spring AOP and IOC container.
Because the best way to learn is practice, I used a working example to introduce how the IOC pattern, as implemented by the Spring IOC container, integrates disparate systems in a loosely coupled manner. As you can see in this example, it is much easier to inject dependencies or services into the credit card account application at work than to build them from scratch.
Stay tuned for the next article in this series, where I'll learn the basics of how the Spring AOP module provides durable support in enterprise applications and lets you get started with spring MVC modules and related plug-ins.
Reference: http://www.ibm.com/developerworks/cn/java/wa-spring1/
Term Description
①Lightweight (lightweight). Spring core containment is less than 1MB in size and can be used in many small devices.
IiNon-invasive (No intrusive). Enhance reusability of application components and reduce reliance on frameworks.
③container (Container). Automatically generate objects and properties based on configuration files, etc., without writing any code to produce objects.
④Inversion of Control (IOC) and Dependency Injection (DI)。 The IOC purpose is to rely on abstraction; the relationship between objects is injected by the container into the specified object based on the configuration file.
⑤AOP (aspect-oriented programming). The agent-and interceptor-based mechanism, combined with the spring IOC, uses a variety of declarative system-level services in the Spring Framework application using the runtime weaving approach.
⑥Persistence layer (persistent). Spring provides DAO, programmatic transactions, and declarative transactions, simplifying the integration and use of ORM Tools (Hibernate, IBATIS).
⑦Java EE services. You can use the various services provided by the Java EE Standard specification and seamlessly combine them.
the benefits of the spring framework
①make the Java EE easy to use and promote good programming habits.
Spring does not re-develop what is already there. Therefore, in spring you will find a packet without logging, no connection pool, and no distributed transaction scheduling. These are available in open source projects (for example Commons Logging is used to do all the log output, or commons dbcp used as a data connection pool) or provided by your application server. For the same reason, we did not provide the O/R mapping layer, and there are good solutions such as Hibernate and JPA.
Iimake existing technologies easier to use.
For example, although we do not reconcile the underlying transaction, we provide an abstraction layer that overrides JTA or any other transaction policy.
③there is no direct competition with other open source projects.
For example, many developers, we have never been happy with struts, and feel that there is room for improvement in the MVC framework. In some areas, such as the lightweight IOC container and the AOP framework, Spring has direct competition, but there are no already popular solutions in these areas. (Spring is a pioneer in these areas.) )
④Spring is portable between application servers. Ensuring portability is always a challenge, but spring avoids any particular platform or non-standardization, and supports users on Weblogic,tomcat,resin,jboss,websphere and other application servers.
⑤easy to decouple and simplify development.
With the IOC container provided by spring, we can control the dependencies between objects by spring, avoiding excessive program coupling caused by hard coding. With spring, users no longer have to write code for these very low-level requirements, such as single-instance pattern classes, attribute file parsing, and can focus more on upper-tier applications.
⑥support for AOP programming.
The AOP functionality provided by spring facilitates aspect-oriented programming, and many features that are not easily implemented with traditional OOP can be easily coped with by AOP.
⑦support for declarative transactions
In spring, we can get rid of the tedious transaction management code, make the transaction management with the declarative way, improve the development efficiency and quality.
⑧Easy testing of programs
Almost all of the testing can be done with non-container-dependent programming, and in spring, testing is no longer an expensive operation, but something that can be done at hand.
⑨Easy integration of a variety of excellent frameworks
Spring does not exclude a variety of excellent open source frameworks, instead, spring can reduce the difficulty of using various frameworks, and spring provides direct support for a variety of excellent frameworks such as struts,hibernate.
⑩reduce the difficulty of using Java EE APIs
Spring provides a thin layer of packaging for many of the hard-to-use Java EE APIs, such as Jdbc,javamail, remote invocation, and so on, and the ease of use of these Java EE APIs is greatly reduced by spring's simple encapsulation.
download, set up spring
http://springframework.org/
Introduction to Spring Framework