Spring's AOP programming--based on annotations, XML configuration file methods

Source: Internet
Author: User
Tags throw exception throwable

AOP (Aspect oriented programming) is a technology for cutting-plane programming. AOP is a useful complement to OOP based on the IOC Foundation. There are 2 ways in which AOP is configured in spring: XML configuration and AspectJ annotation methods.

One, the way XML is configured:

1. Service interface and Services class:
Package cn.edu.nuc.SpringTest.service;


Public interface Demoservice {
public string SayHello (string name);
}




Package Cn.edu.nuc.SpringTest.service.impl;


Import Org.springframework.stereotype.Service;
Import cn.edu.nuc.SpringTest.common.anno.Permission;
Import Cn.edu.nuc.SpringTest.service.DemoService;


@Service
public class Demoserviceimpl implements demoservice{

@Permission (value= "no")
public string SayHello (string name) {
System.out.println ("Hello word ..... +name");
Return "returned value";
}
}


2. Development of Slice type:
Package cn.edu.nuc.SpringTest.interceptor;


Import Java.lang.reflect.Method;
Import Org.aspectj.lang.JoinPoint;
Import Org.aspectj.lang.ProceedingJoinPoint;
Import Org.aspectj.lang.Signature;
Import Org.aspectj.lang.reflect.MethodSignature;
Import cn.edu.nuc.SpringTest.common.anno.Permission;


public class MyInterceptor1 {
Public Object dobasicprofiling (Proceedingjoinpoint pjp) throws throwable{
SYSTEM.OUT.PRINTLN ("Surround Notification entry method----");
Object object=pjp.proceed ();
SYSTEM.OUT.PRINTLN ("Surround notification Exit method------");
return object;
}

Post notification (no need to get return value)
public void doafterreturning (Joinpoint jp,string name,object rvt) {
System.out.println ("Post-notification, Parameters:" +name);
SYSTEM.OUT.PRINTLN ("Rear return:" +RVT);
}

public void doafterthrowing (Joinpoint jp,throwable ex) {
SYSTEM.OUT.PRINTLN ("Exception notification ~~~~~~~~~~~~~~~~~~~");
System.out.println ("Method" + jp.gettarget (). GetClass (). GetName ()
+ "." + jp.getsignature (). GetName () + "throw exception");
System.out.println (Ex.getmessage () +ex.tostring ());
}

Final Notice
public void Doafter (joinpoint jp,string name) {
System.out.println ("Final Notice--------");
}

Pre-notification (no need to get input parameters)
public void Doaccesscheck (Joinpoint JP) {
object[] args = Jp.getargs ();
Signature Signature = Jp.getsignature ();
Methodsignature methodsignature = (methodsignature) signature;
Method Targetmethod = Methodsignature.getmethod ();
if (Targetmethod.isannotationpresent (Permission.class)) {
Permission annotation = targetmethod.getannotation (Permission.class);
System.out.println ("I am Anno:" +annotation.value ());
}
System.out.println ("Pre-notification--------" + ", Parameter:" +args[0]);
}
}


3. XML configuration:
<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/tx
Http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

<context:component-scan base-package= "Cn.edu.nuc.SpringTest"/>
<bean id= "MyInterceptor11" class= "Cn.edu.nuc.SpringTest.interceptor.MyInterceptor1" ></bean>

<aop:config proxy-target-class= "true" >
<aop:aspect id= "Asp1" ref= "MyInterceptor11" >
<aop:pointcut expression= "Execution (* cn.edu.nuc.SpringTest.service.  *.*(..))" Id= "Mycut"/>
<aop:before method= "Doaccesscheck" pointcut= "Execution (* cn.edu.nuc.SpringTest.service). *.*(..))" />
<aop:after method= "Doafter" pointcut= "Execution (* cn.edu.nuc.SpringTest.service). *.*(..)) and args (name) "/>
<aop:after-returning method= "doafterreturning" pointcut= "Execution (* cn.edu.nuc.SpringTest.service). *.*(..)) and args (name) "returning=" rvt "/>
<aop:around method= "dobasicprofiling" pointcut= "Execution (* cn.edu.nuc.SpringTest.service). *.*(..))" />
<aop:after-throwing method= "doafterthrowing" pointcut-ref= "Mycut" throwing= "ex"/>
</aop:aspect>
</aop:config>
</beans>


4. Test:
public class App {
public static void Main (string[] args) {
string[] FileUrl = new string[]{"Classpath*:applicationcontext.xml"};
ApplicationContext appContext = new Classpathxmlapplicationcontext (FILEURL);

Demoserviceimpl ser = Appcontext.getbean (demoserviceimpl.class);
Ser.sayhello ("Lynn 111");
}
}
Note the point:
1) back-to-back notification method, if you want to get the Pointcut method return value, you need to configure returning, and need to maintain the same as the parameter name of the back notification method;
2) in the post-exception notification method, if you want to get the Pointcut method exception, you need to configure throwing, and keep the parameter name of the exception in the method is consistent;
3) in XML, you can pass <aop:pointcut ... Configure multiple pointcuts, and then use different pointcuts in the front, back, surround, and exception notifications in the slice class;
4) In the method of front, rear, exception notification, joinpoint to be the first parameter, (surround notification using proceedingjoinpoint), through Joinpoint with reflection can get the class, method, annotations and other information; (note here, Joinpoint must be placed in the position of the first parameter, when the Joinpoint and Pointcut method parameters, Pointcut method return value, exception objects together, if the joinpoint is not in the first parameter position, then spring will report a failure to bind the pointcut error At:: 0 formal Unbound in pointcut. For example: public void doafterreturning (Joinpoint jp,string name,object rvt), both Joinpoint and Pointcut method parameters, as well as Pointcut method return, Joinpoint Must be in the first place)
5) Get the parameters of the Pointcut method in the notification method of the Slice class:
1. In the notification method, all parameters of the Pointcut method can be obtained by joinpoint;
2. Can be configured in XML and args (name), name and Pointcut method parameter name, the parameter name of the notification method is consistent, so that the parameters in the notification method can get the parameters of the Pointcut method;


Supplementary: The slice class refers to the additional function of the class, such as MyInterceptor1, the notification method is in the slice class, the AOP provisions of the pre-and post-position ... method of marking;

Pointcut class, is to be cut into the business class, such as Demoserviceimpl, the Pointcut method is the Pointcut class, is cut into the method.


Second, the way of annotation:

1. Service interface and Services class: (IBID.)

2. Development of Slice type:

Packagecn.edu.nuc.SpringTest.interceptor;

Importjava.lang.reflect.Method;

Importorg.aspectj.lang.JoinPoint;

Importorg.aspectj.lang.ProceedingJoinPoint;

Importorg.aspectj.lang.Signature;

Importorg.aspectj.lang.annotation.After;

importorg.aspectj.lang.annotation.AfterReturning;

importorg.aspectj.lang.annotation.AfterThrowing;

Importorg.aspectj.lang.annotation.Around;

Importorg.aspectj.lang.annotation.Aspect;

Importorg.aspectj.lang.annotation.Before;

Importorg.aspectj.lang.annotation.Pointcut;

Importorg.aspectj.lang.reflect.MethodSignature;

Importorg.springframework.stereotype.Component;

Importcn.edu.nuc.SpringTest.common.anno.Permission;

@Component

@Aspect

Public Classmyinterceptor {

Pointcut to intercept the class, declare a pointcut, the name of the pointcut is actually a method

@Pointcut ("Execution (* cn.edu.nuc.SpringTest.service). *.*(..))")

Privatevoid Anymethod () {}

Declare a pointcut, the name of the pointcut is actually a method

@Pointcut (value= "Execution (* cn.edu.nuc.SpringTest.service). *. * (java.lang.String)) && args (name))

Privatevoid Nameparamemethod (String name) {}

@Around ("Anymethod ()")

Publicobject dobasicprofiling (Proceedingjoinpoint pjp) throws throwable{

SYSTEM.OUT.PRINTLN ("Surround Notification entry method");

Objectobject=pjp.proceed ();

SYSTEM.OUT.PRINTLN ("Surround Notification Exit method");

Returnobject;

}

Post notification (no need to get return value)

@AfterReturning ("Anymethod ()")

@AfterReturning (pointcut= "Anymethod ()", returning= "result")

Publicvoid doafterreturning (joinpoint jp,string result) {

Object[]args = Jp.getargs ();

Objecttarget = Jp.gettarget ();

Signaturesignature = Jp.getsignature ();

Methodsignaturemethodsignature = (methodsignature) signature;

Method Targetmethod =methodsignature.getmethod ();

Boolean b =targetmethod.isannotationpresent (Permission.class);

if (b) {

Permission Perm =targetmethod.getannotation (permission.class);

String value =perm.value ();

System.out.println ("+value");

}

System.out.println ("=======" +signature.getname () + ";" +jp.getthis (). toString ());

SYSTEM.OUT.PRINTLN ("Post notification:" +args[0]+target.tostring () + "; return value:" +result);

}

@AfterThrowing ("Anymethod ()")

@AfterThrowing (pointcut= "Anymethod ()", throwing= "E")

Publicvoid doafterthrowing (Exception e) {

SYSTEM.OUT.PRINTLN ("Exception Notice:");

}

Final Notice

@After (value= "Anymethod ()")

Publicvoid Doafter (joinpoint JP) {

Object[]args = Jp.getargs ();

System.out.println ("Final Notice: =================" +args[0]);

}

Pre-notification (no need to get input parameters)

@Before ("Nameparamemethod (name)")//The first parameter is the name of the Pointcut, the second is the test gets the input parameter, here is the string type, the parameter name is the same as the name in the method, if you do not get the input parameters, you can not

@Before ("Anymethod ()")//The first parameter is the name of the Pointcut

public void Doaccesscheck (joinpoint jp,string name) {

System.out.println ("Pre-Notification:" +name);

}

}

3. Configuration file:

<?xmlversion= "1.0" encoding= "UTF-8"?>

<beansxmlns= "Http://www.springframework.org/schema/beans"

Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"

xmlns:context= "Http://www.springframework.org/schema/context"

xmlns:tx= "Http://www.springframework.org/schema/tx"

Xsi:schemalocation= "Http://www.springframework.org/schema/beans

Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

Http://www.springframework.org/schema/aop

Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

Http://www.springframework.org/schema/context

Http://www.springframework.org/schema/context/spring-context-3.0.xsd

Http://www.springframework.org/schema/tx

Http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

<context:component-scanbase-package= "Cn.edu.nuc.SpringTest"/>

<!--how AOP is annotated---

<aop:aspectj-autoproxy proxy-target-class= "true"/>

</beans>

Note: You need to use <aop:aspectj-autoproxy proxy-target-class= "true"/> turn on the annotation AOP feature, and if you use IOC, be sure to add proxy-target-class= "true"

4. Test class: (IBID.)

Note the point:

1) back-to-back notification method, if you want to get the Pointcut method return value, you need to add returning in the afterreturning annotation, and need to maintain the same as the parameter name of the back notification method ;

2) in the post-exception notification method, if you want to get the Pointcut method exception, you need to add throwing to the afterthrowing annotation, and keep the exception parameter name in the method.

3) Similarly, in the notification method, Joinpoint is used as the first parameter, for example: public void Doaccesscheck (joinpoint jp,string name);

4) Get the parameters of the Pointcut method in the notification method of the Slice class:

1. In the notification method, all parameters of the Pointcut method can be obtained by joinpoint;

2. Configure Andargs (name) on the annotation on the slice class ,andname to match the parameter name of the Pointcut method parameter name, the notification method , In this way, the parameters of the Pointcut method can be obtained in the notification method.


Pom.xml

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < Modelversion>4.0.0</modelversion> <groupId>cn.edu.nuc</groupId> <artifactId> Springtest</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging > <name>SpringTest</name> <url>http://maven.apache.org</url> <properties> < Project.build.sourceencoding>utf-8</project.build.sourceencoding> <org.springframework.version>      3.1.1.release</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version  > <scope>test</scope> </dependency> <dependency>  <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> < Version>${org.springframework.version}</version></dependency><dependency> <groupId> Org.springframework</groupid> <artifactId>spring-orm</artifactId> <version>${ Org.springframework.version}</version></dependency><dependency> <groupId> Org.springframework</groupid> <artifactId>spring-test</artifactId> <version>${ Org.springframework.version}</version> <type>jar</type> <scope>test</scope></ Dependency><dependency> <groupId>org.aspectj</groupId> <artifactid>aspectjweaver</ Artifactid> <version>1.8.2</version></dependency><dependency><groupId> Com.fasterxml.jackson.core</groupid><artifactid>jackson-core</artifactid><version> 2.2.3</version></dependency><dependency><groupid>com.fasterxml.jackson.core</groupid>< artifactid>jackson-databind</artifactid><version>2.2.3</version></dependency>< Dependency><groupid>com.fasterxml.jackson.core</groupid><artifactid>jackson-annotations </artifactId><version>2.2.3</version></dependency><dependency><groupId> cglib</groupid><artifactid>cglib</artifactid><version>2.2</version></ Dependency> </dependencies></project>


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring's AOP programming--based on annotations, XML configuration file methods

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.