Spring Foundation Concepts AOP and dynamic agent understanding _java

Source: Internet
Author: User
Tags aop commit throwable

First, the agent mode

The agent mode of English is called proxy or surrogate, Chinese can be translated as "agent", the so-called agent, is a person or an institution on behalf of another person or another body to take action. In some cases, a customer does not want or cannot directly refer to an object, and the proxy object can act as a mediator between the client and the target object.

Describe the various agent differences in a simple simulation transaction execution process

1.1 Static agents

The source code is created by the programmer or automatically generated by a particular tool, and then compiled. Before the program runs, the. class file for the proxy class already exists.

Public interface Persondao {

 void Saveperson ();
}
public class Persondaoimpl implements Persondao {

 @Override public
 void Saveperson () {
  System.out.println ("Save Person");
 }


public class Transaction {
 
 void BeginTransaction () {
  System.out.println ("Begin Transaction");
 }
 
 void commit () {
  System.out.println ("commit");
 }

Next, write static proxy class---implement Persondao interface

/**
 * Static proxy class
 * @author QJC */public
class Persondaoproxy implements persondao{

 Persondao Persondao ;
 Transaction Transaction;
 
 Public Persondaoproxy (Persondao Persondao, Transaction Transaction) {
  This.persondao = Persondao;
  This.transaction = transaction;
 }

 @Override public
 void Saveperson () {
  this.transaction.beginTransaction ();
  This.personDao.savePerson ();
  This.transaction.commit ();
 }


Test

/**
 * Test static proxy
 * @author QJC
/public class Testpersonproxy {
 
 @Test public
 void Testsave ( ) {
  Persondao Persondao = new Persondaoimpl ();
  Transaction Transaction = new Transaction ();
  Persondaoproxy proxy = new Persondaoproxy (Persondao, transaction);
  
  Proxy.saveperson ();
 }

Summarize:

1, static agent mode does not achieve the reuse of the transaction

2. Suppose DAO has 100 classes, 100 proxy, how many methods are there in the interface, how many methods to implement at the proxy layer, how many methods to open and how many transactions to submit

3. If a proxy implements more than one interface, if one of the interfaces changes (adding a method), then the proxy should also be changed accordingly

1.2 JDK Dynamic Proxy

Dynamic proxy class: When the program is running, it is created dynamically by using the reflection mechanism.

The JDK dynamic proxy must have four conditions: 1, Target interface 2, Target Class 3, Interceptor 4, proxy class

Persondao interfaces, Persondaoimpl classes, and transaction classes using the previous example

Writing interceptors

Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Method; /** * Interceptor * 1, Target class imported in * 2. * 3, Invoke complete: open transaction, call target object method, transaction Commit * * @author QJC/public class Interce

 Ptor implements Invocationhandler {private object target;//Destination class private Transaction Transaction;
  Public Interceptor (Object target, Transaction Transaction) {this.target = target;
 This.transaction = transaction; The proxy class instance * @param method of the/** * @param proxy target object corresponds to the method instance that invokes the interface methods on the proxy instance * @param args an array of objects passed to the value of the methods parameter on the proxy instance * @ret The return value of the Urn method, no return value is null * @throws throwable/Public Object Invoke (Object Proxy, methods method, object[] args) thro
  WS Throwable {String methodname = Method.getname (); if ("Saveperson". Equals (methodname) | | "Deleteperson". Equals (methodname) | |
   "Updateperson". Equals (methodname)) {this.transaction.beginTransaction ();//Open transaction Method.invoke (target);//Call target method This.transaction.commit (); Commit TRANSACTION} else {Method.invoke (tArget);
 return null;

 }
}

Test

/**
 * Test JDK Dynamic Proxy
 * @author QJC
/public class Testjdkproxy {
 
 @Test public
 void Testsave () {
  /**
   * 1, create a target object
   * 2, create a transaction
   * 3, create an interceptor
   * 4, dynamic generation of a proxy object
   =/Object
  = new Persondaoimpl ();
  Transaction Transaction = new Transaction ();
  Interceptor Interceptor = new Interceptor (target, transaction);
  /**
   * parameter i: Set the code used by the class loader, generally with the same target class loader
   * parameter two: Set proxy class implementation interface, with the target class using the same interface
   * parameter three: Set callback object, when the proxy object's method is called, Invokes this parameter to specify the object's Invoke method/
  Persondao Persondao = (Persondao) proxy.newproxyinstance (
    target.getclass (). getClassLoader (), Target.getclass (), getinterfaces ()
    ,
    Interceptor);
  Persondao.saveperson ();
 }

Summary :

1. Because the proxy class generated by Jdkproxy implements the interface, all the methods in the target class are available in the proxy class.

2, all methods of the generated proxy class intercept all methods of the target class. The contents of the Invoke method in the interceptor are just the components of each method of the proxy class.

3, the use of Jdkproxy mode must have the existence of interfaces.

4. The three parameters in the Invoke method can access the API of the invoked method of the target class, the parameters of the invoked method, and the return type of the invoked method.

Disadvantages:

1, in the interceptor in addition to be able to call the target object of the target method, the function is relatively single, in this case can only handle transactions

2, the Invoke method in the interceptor if judgment statement in the real development environment is not reliable, because once the method many if statements need to write a lot.

1.3 Cglib Dynamic Agent

Persondaoimpl class and Transaction class using the previous example (without interface)

Writing Interceptor Classes

Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;

Import Net.sf.cglib.proxy.MethodProxy;  /** * Cglib Proxy Interceptor * @author QJC/public class Interceptor implements Methodinterceptor {private Object target;

 Agent of the target class private Transaction Transaction;
  Public Interceptor (Object target, Transaction Transaction) {this.target = target;
 This.transaction = transaction; /** * Create target object's proxy object * * @return/public Object Createproxy () {//code enhancement Enhancer enhancer = new Enhancer ( ); This class is used to generate the proxy object Enhancer.setcallback (this); The parameter is the Interceptor Enhancer.setsuperclass (Target.getclass ());//Set the parent class return enhancer.create ();
  Create proxy Object}/** * @param obj Object proxy class Instance * @param method instance of invoking the parent class methods on the proxy instance * @param args an array of objects passed into the method parameter values on the proxy instance  * @param Methodproxy uses it to invoke the parent class * @return * @throws throwable/public object intercept (object obj, methods method, Object[] args, Methodproxy methodproxy) throws Throwable {This.transaction.beginTrAnsaction ();
  Method.invoke (target);
  This.transaction.commit ();
 return null;

 }
}

Test

/**
 * Test cglib dynamic Proxy
 * Generated by Cglib proxy object, proxy class is the subclass of the target class
 * @author QJC/public class
Testcglibproxy {
 
 @Test public
 void Testsave () {
 
  Object target = new Persondaoimpl ();
  Transaction Transaction = new Transaction ();
  Interceptor Interceptor = new Interceptor (target, transaction);
  
  Persondaoimpl Persondaoimpl = (Persondaoimpl) interceptor.createproxy ();
  Persondaoimpl.saveperson ();
 }

Summarize:

1, Cglib is a powerful, high-performance, high-quality code generation Class library. It can extend Java classes and implement Java interfaces at runtime.

2, using Cglib to generate proxy class is the target class subclass.

3, use the Cglib generation proxy class does not need the interface

4, the proxy class generated with Cglib overrides each method of the parent class.

5, the Interceptor intercept method content is exactly the proxy class in the method body cglib and JDK dynamic proxy difference:

Jdk:

The target class and the proxy class implement a common interface

The interceptor must implement the Invocationhandler interface, and the content of the Invoke method body in this interface is the content of the proxy object method body

Cglib:

The target class is the parent class of the proxy class

The interceptor must implement the Methodinterceptor interface, and the Intercept method in the interface is the method body of the proxy class, which uses the bytecode enhancement mechanism to create the proxy object.

Two, facing the plane programming

OOP (object-oriented Programming): Encapsulation, inheritance, polymorphism, abstraction

Encapsulation, the basic management of the Code, modular management. Each class may have its own function, the problem is to talk about looking for someone on the line. From a modification perspective, direct modification of the code can be risky, which is not a long-term plan, most naturally from the type of packaging changes. But the combination of the new type and the old system requires a blood relationship between classes and classes. So this is the inheritance requirement, and by inheritance you can see that these classes are related and have a parent-child relationship. Then, on the basis of inheritance, polymorphism plays a decisive character. Therefore, it is generally believed that the core characteristics of the object-oriented, in fact, polymorphism. In front of a few are doing bedding. Polymorphism is its core feature. By overriding the method, the subclass represents something that extends this level, and it can fit into the old system, which is the reuse of this level of things, new methods, old systems, extensions, and reuse.

AOP (facet-oriented programming):

Aspect-oriented programming is a kind of technology which can dynamically add function to the program without modifying the source code by means of the precompiled runtime dynamic Proxy.

The difference between OOP and AOP:

OOP: An abstract encapsulation of the entities and their attributes and behaviors for the business process to achieve clearer logical unit partitioning.

AOP: Extracting the crosscutting logic in the business process, it is faced with a step or a stage in the process of processing, to obtain the isolation effect of the low coupling between the parts of the logic process. The two design ideas are fundamentally different from each other in the target. AOP achieves the reuse of code blocks.

Spring AOP agent mechanism:

1, if the target object implements several interfaces, Spring uses JDK's Java.lang.reflect.Proxy class proxy.

Advantages: Because there are interfaces, so that the system more loosely coupled

Disadvantage: Create an interface for each target class

2. If the target object does not implement any interfaces, spring uses the Cglib library to generate a subclass of the target object.

Advantage: Because the proxy class is inherited from the target class, there is no need for an interface to exist.

Disadvantage: Because the interface is not used, the coupling of the system does not use the dynamic proxy of the JDK well.

Use the first example of the Persondao interface, Persondaoimpl class, and Transaction class

Writing the spring configuration

 <bean id= "Persondao" class= "Cn.qjc.aop.xml.PersonDaoImpl" ></bean>
 <bean id= "Transaction" class= "Cn.qjc.aop.xml.Transaction" ></bean>
 
 <aop:config>
  <!--pointcut expressions determine the target class-->
  <AOP: Pointcut expression= "Execution (* cn.qjc.aop.xml.persondaoimpl.* (..))" id= "perform"/>
 
  <!--ref points to an object is a slice >
  <aop:aspect ref= "Transaction" >
   <aop:before method= "BeginTransaction" pointcut-ref= "perform" />
   <aop:after-returning method= "Commit" pointcut-ref= "perform"/>
  </aop:aspect>
 </ Aop:config>
 
</beans>

Test

/**
 * Test Spring Dynamic Proxy
 * @author QJC
 *
/public class Transactiontest {

 @Test public
 void Testsave ( {
  ApplicationContext context = new Classpathxmlapplicationcontext ("Cn/qjc/aop/xml/applicationcontext.xml");
  Persondao Persondao = (Persondao) context.getbean ("Persondao");
  Persondao.saveperson ();
 }



Spring AOP Principles

1. When the spring container is started, load two beans to instantiate like a bean
2. When the spring container resolves the configuration file to <aop:config>, parse the pointcut expression and match the bean of the spring container content according to the pointcut expression
3, if the match is successful, create a proxy object for the bean
4, when the client uses Context.getbean to get an object, if the object has a proxy object, then return the proxy object, if there is no proxy object, then return the object itself

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.