Spring Insights 10--using ASPECTJ for AOP development introduction and Case analysis

Source: Internet
Author: User

1. Using ASPECTJ for AOP development

to use the Aspectjs procedure:

1) Add Class Library: Aspectjrt.jar and Aspectjweaver.jar

2) Add an AOP schema.

3) Defining XML Elements:<aop:aspectj-autoproxy>

4) Write the Java class and use the @aspect annotation as the notification

ASPECTJ supports 5 types of notification annotations:

@Before: Pre-notification , executed before method execution

@After: Post notification , executed after method execution

@AfterReturning: Returns a notification that executes after the method returns the result

@AfterThrowing: Exception notification , after the method throws an exception

@Around: Surround Notifications , execute around methods

Configured as a common bean element, the following is a brief description of the terms and usage of these notifications, followed by a case study to anatomy ASPECTJS notification programming.

Front Notification: @Before

@Aspect

public class Audienceadvice {

@Before ("Execution (* welcomeservice.* (..))")

public void Takeseats () {..}

@Before ("Execution (* welcomeservice.* (..))")

public void Turnoffcellphone (Joinpoint jp) {..}

the Joinpoint parameter can access the connection point details, cut into the method name and parameters, and so on .

Jp.gettarget ()//target object

Jp.getthis ()//Current proxy object

Jp.getargs ();//Method invocation parameter

Jp.getsignature (). GetName ()//method signature

Post notification: @After

@After ("Execution (* *). welcomeservice.* (..)) ")

public void Applaud () {..}

The post notification executes after the target method execution is complete. A facet aspect contains a lot of notifications. A post notification indicates that the notification will be woven, whether or not thrown, after the target method has been executed.

back to notifications: @AfterReturning

When the method returns, the notification executes only after the target method returns, if the exception is thrown.

@AfterReturning (pointcut= "", returning= "res")

public void xxx (joinput jp,object res)

The return value can be received in the afterreturning notification. Res is the object that is used to receive the return value.

Surround Notification: @Around

@Around ("Execution (* *). welcomeservice.* (..)) ")

public void Around (Proceedingpointcut JP) {..}

Note: You can control whether the target method is called and return a completely different object, using caution.

Specify the priority level:

@Aspect

@Order (0)

public class xxx{...}

Add @order annotations To specify the precedence of the join plane (the lower the value, the higher the priority)

typical ASPECTJ pointcut expression definitions:

Execution (* cn.itcast.welcomeserviceimpl.* (..))

Execution (Public * *.. Welcomeserviceimpl.* (..))

Execution (public void *: Welcomeserviceimpl.* (*))

Execution (public void *: *service.* (double,double)).

pointcut expression arithmetic (&& | |!)

@Pointcut ("Execution (..) | | Execution (..) ")

Reusing pointcut Definitions

Note the pointcut to an empty method body, and reference it elsewhere.

Defining pointcuts

@Pointcut ("Execution (* *). welcomeservice.* (..)) ")

public void Performpoint () {}

@Before ("Performpoint ()")

@After ("Performpoint ()")

Introduce notifications:

@Aspect

public class Myaspectjintroduction {

@DeclareParents (value= "*.. *service* ", Defaultimpl=modifydateimpl.class)

Private Modifydate MD;

}

value: Specifies which classes can apply the property

Defaultimpl: specifying an implementation class for an interface

developing AOP using Pojo+xml

Note-based ASPECTJ declarations take precedence over XML configurations.

XML-based configuration is spring proprietary. ASPECTJ is getting more and more support,

Have better reusability.

2.ASPECTJ Case Study

The following two cases illustrate two different ways of using ASPECTJ to develop projects;

First, the target classes UserService and Userserviceimpl for the object abstraction interfaces and abstract interfaces used in both methods are listed, and the interface and implementation classes required for reference notifications

Userservice.java

Package Www.csdn.spring.proxy.advice.aspectjs;
	Public interface UserService {public void Save (Object entity);
	public void update (Object entity);
	public void Delete (Object entity);
public void getallobjects ();

} Userserviceimpl.java package Www.csdn.spring.proxy.advice.aspectjs; public class Userserviceimpl implements UserService {@Override public void Save (Object entity) {SYSTEM.OUT.PRINTLN (
	"---Save Method: Save ()---");
	@Override public void Update (Object entity) {SYSTEM.OUT.PRINTLN ("---Update method: Updated ()---");
		} @Override public void Delete (Object entity) {SYSTEM.OUT.PRINTLN ("---Delete method: Delete ()---");
	int i = 1/0;
	} @Override public void Getallobjects () {System.out.println ("---Find all methods: getallobjects ()---");

The following is the interface and implementation class that the reference notification requires: Auditable.java package Www.csdn.spring.proxy.advice.aspectjs;

Import Java.util.Date;
	Public interface Auditable {public void setDate (date date);

Public Date getDate (); } Auditableimpl.java Package Www.csdn.spring.proxy.adviCe.aspectjs;

Import Java.util.Date;

Import Org.springframework.aop.support.DelegatingIntroductionInterceptor;
	public class Auditableimpl extends Delegatingintroductioninterceptor implements Auditable {private date date;
	@Override public void setDate (date date) {this.date = date;
	} @Override Public Date getDate () {return date;

 }
}


The first way: Use the advice notification class: Adviceservice.java

Package Www.csdn.spring.proxy.advice.aspectjs;
Import Org.aspectj.lang.ProceedingJoinPoint;
Import Org.aspectj.lang.annotation.After;
Import org.aspectj.lang.annotation.AfterReturning;
Import org.aspectj.lang.annotation.AfterThrowing;
Import Org.aspectj.lang.annotation.Around;
Import Org.aspectj.lang.annotation.Aspect;
Import Org.aspectj.lang.annotation.Before;
Import Org.aspectj.lang.annotation.Pointcut;

Import Org.junit.experimental.theories.Theory;
	@Aspect public class Adviceservice {//Pre-notification @Before (value = "Execution (* userserviceimpl.save (..))")
	public void Beforemethod () {System.out.println ("-------Open transaction-------"); }//Post notification @After (value = "Execution (* www.csdn).
	Userserviceimpl.save (*)) "public void Aftermethod () {System.out.println ("-------End transaction--------"); 
		}//Surround notification @Around (value = "Execution (* userserviceimpl.update (*))") public void Aroundmethod (Proceedingjoinpoint pjp) {
		System.out.println ("-=-=-=-before-=-=-=-= safe handling");
		try {pjp.proceed (); } catch (ThrOwable e) {e.printstacktrace ();
	} System.out.println ("-=-=-=-=-after-=-=-=-=-= safe handling"); }//Define a method that specifies the location of the pointcut @Pointcut ("Execution (* *). Userserviceimpl.delete (*)) "public void Pointcuts () {}////The following two notifications refer to the Pointcut method//Exception notification//@AfterThrowing (" pointcuts () ") Publ
	IC void Throwsmethod () {SYSTEM.OUT.PRINTLN ("Exception notification execution");
	}*/@AfterReturning ("pointcuts ()") public void afterruning () {System.out.println ("========= return value ========");
 }
}


using the AspectJ most important file, the spring-related configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- Beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring -aop.xsd "> <!--configuration notification of the bean, actually ASPECTJS automatically scan all beans, go to the bean with slices---<bean id=" Adviceservice "class=" Www.csdn.spring.proxy.advice.aspectjs.AdviceService "/> <!--Introducing notification FACETS--<bean id=" Auditableservice "class = "Www.csdn.spring.proxy.advice.aspectjs.AuditableService"/> <!--real-World Theme target Object--<bean id= "Userserviceimpl "class=" Www.csdn.spring.proxy.advice.aspectjs.UserServiceImpl "/> <!--use Aspectjs to configure auto-agent--&LT;AOP:
 Aspectj-autoproxy/> </beans>


Test class Advisetest.java

Package Www.csdn.spring.proxy.advice.aspectjs;

Import java.util.Date;

Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Advisetest {

	@Test public
	void TestUser () {

		ApplicationContext context = new Classpathxmlapplicationcontext (
				"Spring-aspectjs.xml");
		The proxy theme, which uses the same interface class implemented by the proxy theme and the real theme to receive the created proxy theme, is to create a target class
		userservice userservice = Context.getbean ("Userserviceimpl ",
				Userservice.class);
		
		Userservice.save (null);
		/*userservice.update (null);
		try{			
			userservice.delete (null);
		} catch (Exception e) {
			
		}		
		userservice.getallobjects (); *
		
		//Introduce notification test
		Auditable Auditable = (Auditable ) UserService;
		Auditable.setdate (New Date ());
		System.out.println (Auditable.getdate ());
	}

}


The second way: use Pojo-xml to write ASPECTJ notification class Adviceservice.java

Package www.csdn.spring.proxy.advice.aspectjs.pojoxml;

Import Org.aspectj.lang.ProceedingJoinPoint;

public class Adviceservice {
	
	//Pre-notification public
	void Beforemethod () {
		System.out.println ("-------Open transaction-------" );
	}
	
	Post-notification public
	void Aftermethod () {
		System.out.println ("-------End transaction--------");
	}
	
	Surround notification public
	void Aroundmethod (Proceedingjoinpoint pjp) {
		System.out.println ("-=-=-=-= before security Processing");
		try {
			pjp.proceed ();
		} catch (Throwable e) {
			e.printstacktrace ();
		}
		System.out.println ("-=-=-=-=-after-=-=-=-=-= safe handling");
	}
	Exception notification public
	void Throwsmethod () {
		System.out.println ("Exception notification Execution");
	}
	Notification with return value public
	void Afterruning () {
		System.out.println ("========= return value ========");}
}

use Pojo-xml AspectJ One of the most important files, spring-related configuration files

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- Beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring -aop.xsd "> <!--configuration notification of the bean, actually ASPECTJS automatically scan all beans, go to the bean with slices---<bean id=" Adviceservice "class=" WWW.CSD N.spring.proxy.advice.aspectjs.pojoxml.adviceservice "/> <!--real-World Theme target Object--<bean id=" Userserviceimpl "cl ass= "Www.csdn.spring.proxy.advice.aspectjs.pojoxml.UserServiceImpl"/> <!--using pojo-xml Aspectjs to configure auto-agent----& lt;aop:config> <!--configuring facets--<aop:aspect ref= "Adviceservice" > <!--Introducing Notifications-<aop:de Clare-parents types-matching= "*. *service* "imPlement-interface= "Www.csdn.spring.proxy.advice.aspectjs.pojoxml.Auditable" default-impl= " Www.csdn.spring.proxy.advice.aspectjs.pojoxml.AuditableImpl "/> <!--cut-in points, you can write several different pointcuts at the same time--&LT;AOP
				:p ointcut expression= "Execution (* www.csdn..UserServiceImpl.save (..))"
				Id= "Mypcut"/> <aop:pointcut expression= "Execution (* www.csdn..UserServiceImpl.update (..))" Id= "Mypcuts"/> <!--Weaving Notification method: Specify methods; Pointcut-ref Introducing Pointcuts--<aop:before method= "Beforemethod" pointcut-ref= "Mypcut"/> <aop:after method= "afte Rmethod "pointcut-ref=" Mypcut "/> <aop:after method=" afterruning "pointcut-ref=" MyPcut "/> <aop:around m Ethod= "Aroundmethod" pointcut-ref= "mypcuts"/> <aop:after-throwing method= "Throwsmethod" pointcut-ref= "
 Mypcuts "/> </aop:aspect> </aop:config> </beans>


Test class Advisetest.java

Package www.csdn.spring.proxy.advice.aspectjs.pojoxml;

Import java.util.Date;

Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

public class Advisetest {

	@Test public
	void TestUser () {

		ApplicationContext context = new Classpathxmlapplicationcontext (
				"Spring-pojo*.xml");
		The proxy theme, which uses the same interface class implemented by the proxy theme and the real theme to receive the created proxy theme, is to create a target class
		userservice userservice = Context.getbean ("Userserviceimpl ",
				Userservice.class);
		
		Userservice.save (null);
		Userservice.update (null);
		
		Introduction Notification Test
		Auditable Auditable = (Auditable) userservice;
		Auditable.setdate (New Date ());
		System.out.println (Auditable.getdate ());
	}

}


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.