Research and application of Spring framework and AOP thought

Source: Internet
Author: User
Tags aop object bind implement interface key throwable domain
   SummaryThis paper analyzes the AOP thought and transaction management contained in spring framework, and illustrates the feasibility and effectiveness of dynamic Proxy mode by implementing lock/unlocking operation for a business object.

   Key WordsAOP; crosscutting concerns; control reversal; dynamic proxy

   Introduction

Aspect oriented Programming (AOP) is one of the most popular topics in computer technology in recent years. The history of its development begins with the use of academic and research institutions, and the current popular Spring application framework integrates AOP thinking into the design and development of the entire framework. While the use of the spring framework has brought benefits and convenience to our programming, there is a problem, for starters, the so-called "control reversal" is not a good name to be able to words too literally, "dependency injection" is the same, and precisely because of this, It is difficult for beginners to understand and master these names and their usage in a short time, and it is also difficult to understand AOP in order to use AOP functions. For the above reasons, we can think of a simple way to apply the best ideas in the spring framework to the places we need to use, and bypass the not-so-easy spring framework. This article will be around the above mentioned questions to give the author's views and views.

   AOP thinking and aspect-oriented programming

AOP is an extension of the Gof four-group design pattern, which is designed to reduce the coupling between code, to increase the flexibility and reusability of the program, and AOP is actually a realization of the goal that the design pattern pursues. The so-called separation concern is to separate a general demand function from the related classes, at the same time, can make many classes to share a behavior, once the behavior changes, do not have to modify many classes, as long as the modification of this behavior can be. AOP is this way of implementing decentralized attention, which encapsulates "concerns" in "aspects."

Object-oriented Programming (OOP) is an improvement on the basis of process-oriented programming, while aspect-oriented programming (AOP) is an innovative software development method based on object-oriented programming (OOP) method. While AOP and OOP are literally similar, they are two design ideas for different domains. OOP (object-oriented programming) abstracts and encapsulates entities and their attributes and operations that exist in the problem domain as well as in the business process. The core concept of object-oriented is the vertical structure, which aims to achieve a more clear and efficient division of logical units, while AOP extracts the facets of the business process, for example, An operation is involved in each module, and this operation can be seen as "crosscutting" in the system. In many cases, these operations are not necessarily relevant to the business logic or are not part of the logical operation, and the object-oriented approach is difficult to deal with. AOP separates these operations from business logic, allowing programmers to focus on the processing of business logic while writing programs, and using AOP to automatically couple crosscutting concerns across modules. AOP is faced with the process of a certain step or stage, the different stages of the domain to isolate, has been the logic process of the low coupling between the isolation effect, and aspect-oriented programming in the target has a fundamental difference. The central idea of AOP is to separate the business logic processing parts of the application from the common services that support them, known as "crosscutting concerns," which run through the needs of multiple vertical modules in the program.

To develop using an AOP mechanism, you need to understand the aspects first, break down requirements into general and crosscutting concerns, separating core module-level concerns from system-level crosscutting concerns, and then implementing these concerns independently, and then weaving the business logic code and the crosscutting focus code together with tools Form the final procedure. The coding time and repetition can be reduced by aspect-oriented programming.

   the spring framework that has now been formed

1, the characteristics of spring framework

The spring framework is now so popular, on the one hand, because spring provides a comprehensive and very mature lightweight application infrastructure and provides strong support for complex application development. In addition, from the perspective of practical application development, spring's biggest advantage is that it is extracted from the actual project development experience, it provides a rich class library, can save the coding quantity greatly, it is an efficient, highly reusable application framework. One of the most compelling and interesting areas of the spring framework is the design idea of a control reversal (Ioc=inverse of controls) or dependency injection (di=dependence injection), which is a pretty good design idea, The "Hollywood" principle: You don't have to come to me on your own initiative, I'll let you know. But with just such a simple design pattern that does not make spring so successful, spring's most successful place is the most widely used AOP application, the business management mechanism based on AOP implemented in spring, which makes spring AOP has become an extremely bright spot in the application framework.

2. The embodiment of AOP thought in spring frame

The concept of AOP and what is called crosscutting concerns are described earlier in this article, and transaction management is an example of a crosscutting concern that cuts across multiple objects in Java application.

2.1 Transaction Management

For Java EE applications, transactions typically have two modes of processing: Transactions that depend on a particular transaction resource and parameterized transaction management of dependent containers. Here we omit the description of the first approach, directly to the second way, that is, relying on the container of parameterized transaction management to illustrate the author's point of view.

What can spring transaction management bring to us?

As anyone who understands spring knows, Spring has no impact on traditional transactional resource transactions, so we can write and run the code successfully.

For parameterized transaction management that relies on containers, spring can be used to help manage transactions without using EJBS. Spring itself is also a container, but spring is a lightweight container for the cost of the EJB container, it can replace EJBs, and by using AOP to provide declarative transaction management, container based transaction management can be implemented through spring (essentially, Spring's transaction management is based on dynamic AOP. The biggest difference between spring and EJB is that spring can implement transaction management for any Java class without converting it into a standard EJB, and second, spring transaction management does not rely on specific transaction resources to make the application and deployment of the system more flexible.

2.2 Implementation of dynamic proxy mechanism

The AOP support provided in the spring framework is based on the dynamic AOP mechanism, in which the corresponding processing code is inserted before and after the target object's method invocation. AOP proxies can be based on either JDK dynamic agents or cglib proxies. Spring is implemented by default based on the Java Dynamic Proxy pattern so that any interface can be represented. Based on the SPIRNG framework of application development, programmers will have a natural tendency to implement interface-oriented programming rather than classes, business objects are often implemented one or more interfaces, which is also a good programming practice. Spring can also implement AOP proxies based on Cglib, so that the proxy is a class rather than an interface. If a business object does not implement an interface, then Cglib will be used.

Let's first analyze the implementation principle of spring transaction management mechanism. Because spring's built-in AOP is implemented by default in dynamic proxy mode, we first analyze the implementation of the dynamic proxy pattern. The core of dynamic proxy mode is that there is no interface or class reference associated with the specific application layer in the code, as mentioned above, this proxy class applies to the implementation of any interface. Let's take a look at the example below. public class Txhandler implements Invocationhandler {

Private Object Originalobject;
public object bind (Object obj) {
This.originalobject = obj;
Return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this);
}

public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
Object result = null;
if (!method.getname (). StartsWith ("save")) {
UserTransaction tx = NULL;
try {
tx = (usertransaction) (New InitialContext (). Lookup ("Java/tx"));
result = Method.invoke (Originalobject, args);
Tx.commit ();
catch (Exception ex) {
if (null!= TX) {
try {
Tx.rollback ();
catch (Exception e) {
}
}
}
} else {
result = Method.invoke (Originalobject, args);
}
return result;
}
}
Let's analyze the key to the above code.

Let's take a look at this piece of code:

Return Proxy.newproxyinstance (
Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this);
The Java.lang.reflect.Proxy.newProxyInstance method dynamically constructs a proxy class instance return based on the incoming interface type (Obj.getClass.getInterfaces ()). This also explains why the dynamic proxy implementation requires that the object to which it is represented must implement an interface. This proxy class instance is dynamically constructed in memory and implements all the interfaces contained in the list of incoming interfaces.

Then analyze the following code:

public object invoke (object proxy, Method method, object[] args)
Throws Throwable {
......
result = Method.invoke (Originalobject, args);
......
return result;
}


The Invocationhandler.invoke method will be triggered before the method of the proxy class is invoked. In this way, we can do some processing before and after the invocation of the proxy class method, as shown in the code, passing the currently invoked method in the parameters of the Invocationhandler.invoke method and the parameters of the invoked method. At the same time, the original method implementation of the proxy class can be invoked through the Method.invoke method. This allows you to write any desired action before and after the method invocation of the proxy class.

The principle of spring's transaction management mechanism is to load all beans that require transaction management through such a dynamic proxy, and to determine the method name of the current invocation based on the configuration in the Invoke method. And then add the appropriate transaction management code to it before and after the Method.invoke method, which realizes the spring-style transaction management. The AOP implementations in spring are more complex and flexible, but the rationale is consistent.

Application example of 3.AOP thought and dynamic agent mode

We analyze the basic reality principle of the transaction management mechanism of Spring framework. Although the spring framework embodies some of the things that are not noticed in the current popular framework, the spring framework has an obscure and fatal problem. The above research on some basic principles of spring framework has brought us some enlightenment. If we don't use the huge spring framework directly, we apply AOP ideas into the spring framework directly to the program, bypassing the high threshold of the spring framework, and taking advantage of the advanced design concepts in the spring framework, to kill both.

Let's look at a piece of code to write an instance of the dynamic Proxy based AOP implementation. Suppose there is now a Userdao interface and a userdaoimp with its implementation class.

Userdao.java:

Public interface Userdao {
public void Saveuser (user user);
}

Userdaoimp.java:

public class Userdaoimp implements userdao{
public void Saveuser (user user) {
......
}
}
We need to add a lock to a business object in the Saveuser method, such as locking and unlocking before and after the Saveuser. Agent mode is a good choice without affecting external logic and making any changes to existing code. However, if there are many similar interfaces, the face of each interface to implement a similar proxy, it is a cumbersome and tasteless process of coolie. Think back to Spring's design philosophy in dealing with this issue it is not difficult to imagine that using dynamic proxy mode is a clever solution to this problem.

public class Aophandler implements Invocationhandler {
private static Log logger = Logfactory.getlog (Aophandler.class);
Private List interceptors = null;
Private Object Originalobject;
public object bind (Object obj) {
This.originalobject = obj;
Return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (). this);
}
public object invoke (object proxy, Method method, object[] args) throws Throwable{object Result=null
if (Method.getName.startsWith ("Saveuser")) {
Lock ();
Result=method.invoke (This.originalobject,args);
Unlock ();
}
return result;
}
private void Lock () {
Logger.info ("Lock object!");
}
private void Unlock () {
Logger.info ("Unlock object!");
}
}
The above code does not appear with the interface associated with the specific application layer and the reference to the class, so it applies to all classes. This solves the disadvantage of using static proxy class to realize.

   Summary and Prospect

Above we discussed the Spring framework based on dynamic AOP mechanism implementation and dynamic proxy mechanism application, around the implementation and application of AOP, has always been a hot topic, that is, rights management. The spring framework is doing a pretty good job of supporting AOP at the moment, but there has always been an embarrassing problem that has not yet been resolved, and that is that there is not yet a complete rights management component. Think carefully, this is not the bottleneck of AOP, but because the form of authority management is too flexible and complex and changeable, the system of authority management logic is varied and diverse, we can not make a unified management and operation. On the other hand, authority management as an independent section appears too large, need further segmentation design, design process complex, difficult to achieve. So we are still looking forward to the idea of AOP in the field of authority management can be a breakthrough application and expansion.

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.