Spring AOP Dynamic Agent principle and implementation method

Source: Internet
Author: User
Tags aop object model throwable

AOP: Slicing, aspect oriented, interface-oriented is a crosscutting technology
Crosscutting Technology Application:
1. Transaction management: (1) Database transactions: (2) Programming transactions (3) declaring things: Spring aop--> declaring things
2. Log processing:
3. Security verification: Spring AOP---OOP upgrades

Static agent Principle: Target object: Invoke business Logic proxy object: Log Management
Presentation Layer Call---> Proxy object (log management)--> call target object

Dynamic Agent principle: Spring AOP adopts dynamic proxy to implement
(1) Implement Invocationhandler interface

(2) Create proxy class (via Java API)

Proxy.newproxyinstance (Dynamic loading proxy class, proxy class implementation interface, using handler);

(3) Invoke Invoke method (virtual machine automatically invoke method)

Log processing
Call target Object
Method.invoke ("target object", "parameter");
Log processing

--> the target object---(return information) by proxy Object-(Request information)----> Proxy Object

the basic concepts in Spring dynamic proxy

1, Focus point (concern)
   a focus can be a specific issue, concept, or point of interest in an application. All in all, the application must reach a goal
   security validation, logging, transaction management is a concern
   in OO applications, the focus may have been modularized by code and may be scattered throughout the object model
2. Crosscutting concerns (crosscutting concern)
   How a focus implementation code is scattered across multiple classes or methods
3, Aspect (aspect)
   One aspect is the modularity of a crosscutting concern, which would have been scattered everywhere,
   code to implement this concern is structured in one place
4, recommendation (advice) notification
   advice is point Cut execution code, is the implementation of the specific implementation of the
5, pointcut (pointcut)
   to specify where a recommendation to use
6, weaving (weaving)
   will aspect (aspects) Procedure applied to the target object
7, join Point
  A point in the process of program execution  

Notification Type:
try{
Forward notification
Surround notification
Calling the target object method
Surround notification
Post notification
}catch () {
Exception notification
}finally{
Termination notification
}

Flow Chart

example of static agent principle:

Project Structure Chart:

Iuserserv Interface Code

Public interface Iuserserv {
	list<user> findalluser ();
	int Deleteuserbyid (user user);
	int saveuser (user user);
}


Userservimpl Implementation Class Code

public class Userservimpl implements Iuserserv {public
	int Deleteuserbyid (user user) {
		System.out.println ("* * Execute Delete method ")";
		return 0;
	}
	Public list<user> Findalluser () {
		System.out.println ("******* Execute Query method *******");
		return null;
	}
	public int saveuser (user user) {
		System.out.println ("******* execution Add Method ********");
		return 0;
	}
}

Userservproxyimpl Implementation Class Code

Proxy class: Completion log Output Public
class Userservproxyimpl implements Iuserserv {
	//Access target object (USERSERVIMPL)
	//proxy object ( USERSERVPROXYIMPL)
	//Create target object
	private Iuserserv iuserserv//= new Userservimpl ();

	Public Userservproxyimpl (Iuserserv iuserserv) {
		this.iuserserv = Iuserserv;
	}
	public int Deleteuserbyid (user user) {
		beforelog ();
        Invokes the method
		Iuserserv.deleteuserbyid (user) in the target object;
		Afterlog ();
		return 0;
	}

	Public list<user> Findalluser () {
		beforelog ();
		Invokes the method Iuserserv.findalluser () in the target object
		;
		Afterlog ();
		return null;
	}

	public int saveuser (user user) {
		beforelog ();
		Invokes the method
		Iuserserv.saveuser (user) in the target object;
		Afterlog ();
		return 0;
	}

	private void Beforelog () {
		System.out.println ("Start Execution");
	}
	
	private void Afterlog () {
		System.out.println (execution complete);
	}

Actiontest Test Class Code

public class Actiontest {public
	static void Main (string[] args) {
		//user Access Proxy object---Information-> target object
		iuserserv Iuserserv = new Userservproxyimpl (new Userservimpl ());
		Iuserserv.findalluser ();
	}

Run Result:

Start execution
Execute Query method *******
Execution completed
two. Dynamic Proxy instance

Project Structure Chart:

The Iuserserv interface code and the Userservimpl implementation class code are the same as the above code

Loghandler Class Code

public class Loghandler implements Invocationhandler {
	//target object
	private object TargetObject;
	/**
	 * Create dynamic proxy class
	 * @return object (proxy Class)
	 *
	/public Object Createproxy (object targetobject) {
		This.targetobject = TargetObject;
		Return Proxy.newproxyinstance (
				targetobject.getclass (). getClassLoader (), 
					Targetobject.getclass (). Getinterfaces (), this);
	}
	@Override Public
	object Invoke (Object proxy, Method method, object[] args)
			throws Throwable {
		Object obj = null;
		try {
			beforelog ();
			OBJ: The target object---the return value of the > Proxy object---> The information returned to the caller
			//this.invoke ("target Object", "the proxy object passes parameters to the target object");
			Invokes the method
			obj = Method.invoke (targetobject, args) in the target object;
			Afterlog ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
		return obj;
	}
	
	Log Management method
	private void Beforelog () {
		System.out.println ("Start Execution");
	}
	
	private void Afterlog () {
		System.out.println (execution complete);
	}


Actiontest Test Class Code:

public class Actiontest {public
	static void Main (string[] args) {
		//Create proxy object Iuserserv
		Loghandler handler = new Loghandler ();
		Iuserserv Iuserserv = (iuserserv) handler.createproxy (New Userservimpl ());
		Iuserserv.deleteuserbyid (New User ());
	}

Run Result:
Start execution
Execute Delete method Hu Jintao
Execution completed
three. Spring AOP usage (prior to 2.x version)

Project Structure Chart:



The Iuserserv interface code and the Userservimpl implementation class code are the same as the above code

Configuration steps:

1. Configure target object (Applicationcontext.xml)

<bean id= "Userservtarget" class= "Com.tarena.biz.impl.UserServImpl"/> 

2, Configuration Notice
(a) prior notice (Beforelogadvice)

public class Beforelogadvice implements Methodbeforeadvice {
	 /**
	    * Methods method: Calling the target object by means of
	    * object[] args: Parameter list sent to target object target
	    : target object */public
	void Before (method method, object[] args, object target)
			Throws Throwable {
		beforelog ();
	}
	private void Beforelog () {
		System.out.println ("Start Execution");
	}


(b) post-notification (Afterlogadvice)

public class Afterlogadvice implements Afterreturningadvice {
	  /**
	    * Object returnvalue: Target object return value
	    *  Methods: Target object Method name
	    *  object[] args: target object argument list * Object target  : target object/
	    public
	Void Afterreturning (Object ReturnValue, Method method,
			object[] args, object target) throws Throwable {
		afterlog () ;
	}
	private void Afterlog () {
		System.out.println (execution complete);
	}

(c) Let the container manage notifications in the spring container (applicationcontext.xml)

<!--definition notification-->
		<!---->
		<bean id= "Beforelogadvice" Com.tarena.advice.BeforeLogAdvice "/>
		<!--post notification--> <bean id=" Afterlogadvice "class="
		Com.tarena.advice.AfterLogAdvice "/>


3. Configure proxy objects (Applicationcontext.xml)

<!--agent function: Generate proxy class, weave into the notification-->  
  <bean id= "Userservproxy" 
   class= " Org.springframework.aop.framework.ProxyFactoryBean ">
   <property name=" Interfaces ">
   <!-- Can add multiple interfaces-->
    <list>
     <value>com.tarena.biz.IUserServ</value>
    </list>
   </property>
   <!--introduce notice-->
   <property name= "Interceptornames" >
    <list>
     <value>beforeLogAdvice</value>
     <value>afterLogAdvice</value>
    </list >
   </property>
   <!--target object-->
   <property name= "target" ref= "Userservtarget"/>
  </bean>


4. Visit ()
Spring container: Invoking-->---> Target object via proxy object
Programmer: Access Proxy Object

Test Class (Actiontest):

public class Actiontest {public
	static void Main (string[] args) {
		ApplicationContext ac = new Classpathxmlapplica Tioncontext ("Applicationcontext.xml");
		Iuserserv Iuserserv = (iuserserv) ac.getbean ("Userservproxy");
		Iuserserv.deleteuserbyid (New User ());
		Iuserserv.findalluser ();
	}

Run Result:

Start execution
Execute Delete method Hu Jintao
Execution completed
Start execution
Execute Query method *******
Execution completed
four. Spring AOP uses (after the 2.x version) to add an additional two jar packages in this way,

the storage location is under the Spring-framework-2.5.6.sec01\lib\aspectj folder.

Project Structure Chart


The Iuserserv interface code and the Userservimpl implementation class code are the same as the above code

In Logadvice

public class Logadvice {public
	void Beforelog () {
		System.out.println ("Start Execution");
	}
	public void Afterlog () {
		System.out.println (execution complete);
	}

In Applicationcontext.xml

<!--spring2.x after-->
	<!--target object-->
	<bean id= "Userservimpl" Com.tarena.biz.impl.UserServImpl "/>
	<!--notice-->
	<bean id=" Logadvice "class=" Com.tarena.advice.LogAdvice "/>
	
	<aop:config>
		<aop:aspect id=" Logaspect "ref=" Logadvice ">
			<!--pointcut-->
			<aop:pointcut id= "beforepointcut" expression= 
	    "Execution (* saveuser* (..))" />
	    <aop:pointcut id= "afterpointcut" expression= 
	    "Execution (* saveuser* (..))" />
			
			<!--weaving (notification action on pointcut)-->
			<aop:before method= "Beforelog" pointcut-ref= "Beforepointcut"/>
			<aop:after method= "Afterlog" pointcut-ref= "Afterpointcut"/>
		</aop:aspect>
	</AOP: Config>

Test class:

public class Actiontest {public
	static void Main (string[] args) {
		ApplicationContext ac = new Classpathxmlapplica Tioncontext ("Applicationcontext.xml");
		Iuserserv Iuserserv = (iuserserv) ac.getbean ("Userservimpl");
		Iuserserv.deleteuserbyid (New User ());
		Iuserserv.findalluser ();
		Iuserserv.saveuser (New User ());
	}

Run results
Execute Delete method Hu Jintao
Execute Query method *******
Start execution
Execute Add Method ********
Execution completed

Note: If you want to add a log file before and after all the methods in the business layer, you need to change to the following configuration

<aop:pointcut id= "Beforepointcut" 
	    expression= "Execution (* com.tarena.biz.*.* (..))" />
	    <aop:pointcut id= "afterpointcut" expression= 
	    "Execution (* com.tarena.biz.*.* (..))" />


Run Result:

Start execution
Execute Delete method Hu Jintao
Execution completed
Start execution
Execute Query method *******
Execution completed
Start execution
Execute Add Method ********
Execution completed


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.