Spring AOP Code Instance

Source: Internet
Author: User
Tags aop arrays object object throwable

AOP (aspect-orientedprogramming, plane-oriented programming, many people like to say aspect-oriented programming, I think facets easier to explain AOP.) )

Aspect-oriented programming, effectively reduce the coupling between the code, easy to maintain; For example: We are accustomed to add some log information in the code, in case of errors in the program to quickly find the problem, usually in the request to enter the method of the print log, log out before the exit, and print the log On error, then the problem comes , each method needs to print the log, these same parts can be used as a slice, by configuring the pointcut to trigger the required functionality, for example, I need to print when requesting access to the method, you can use the pre-notification in the AOP to do so, do not need to write in each method, and then the reference can be configured.

AOP Code Examples:

1. Creating a console program; importing packages

2. Create an interface

Package com. Aspecttest.service;
Public interface Personserver {public
	void Save (String uname,int age);	
}
3. Implementation of the interface

Package com. Aspecttest.service;
public class Personserverimpl implements personserver{
	@Override public
	void Save (String uname,int age) {
		int a=0;
		Age= age/a;//Open the above two lines error, can trigger exception notification
		SYSTEM.OUT.PRINTLN ("Come in Personserverimpl Save Method ...");}

4. Create (AOP) Slice classes

Package com.
ASPECTTEST.AOP;
Import Java.util.Arrays;
Import Org.aspectj.lang.JoinPoint;
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.springframework.stereotype.Component; @Aspect//Declaration This is a facet @Component//Declaration This is a component that refers to ... You can remove the public class Aspectintercepter {@Pointcut (value= "Execution (* com).
	  aspecttest.service.personserverimpl.* (..)) ") private void PointCut () {///define a pointcut following the notification directly into the Pointcut method PointCut can personserverimpl all the methods below}//Surround notification (connected to the tangent The in point begins execution, the next step enters the front notification, and the next step is to perform the action method) @Around (value= "PointCut ()") Public Object dobasicprofiling (Proceedingjoinpoint PJ
	        p) throws throwable{System.out.println ("@Around into surround notice ..."); Object objECT = Pjp.proceed ();//Execute the method System.out.println (Pjp.getthis () + "End of operation, exit method; surround [@Around].
	        ...");
	    return object; 
	        }//Pre-notification (go into surround execution, next execution method) @Before (value= "PointCut ()") public void Doaccesscheck (Joinpoint joinpoint) {
	    System.out.println ("@Before Front Notification:" +arrays.tostring (Joinpoint.getargs ())); }//Exception notification (executed on Error) @AfterThrowing (value= "PointCut ()", throwing= "ex") public void Doafterthrow (Joinpoint Joinpo
	        Int,throwable ex) {System.out.println ("@AfterThrowing exception notification (exception notification)" +arrays.tostring (Joinpoint.getargs ()));
	    System.out.println ("@AfterThrowing exception information:" +ex); }//Post notification (returned before execution) @After (value= "PointCut ()") public void After () {System.out.println ("@After post notification
	    ..."); }//Final notification (normal return notification, last execution) @AfterReturning (value= "PointCut ()") public void Doafter () {System.ou T.println ("@AfterReturning Final notice ...
 End! ");}}

5. Configure the AOP configuration file

<?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 "
	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-4.0.xsd/
		http Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd " >
	<!--make AspectJ annotations work--
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
 
    < Bean id= "Personservicebean" class= "com. AspectTest.service.personServerImpl "/>  
    <bean id=" myinterceptor "class=" com. AspectTest.aop.AspectIntercepter "/> 
    
</beans>
6. Create a test class

Package com. Aspecttest;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import com. AspectTest.service.personServer;
public class Springaoptest {
	    @Test public
	    void Inteceptortest () {
	        ApplicationContext ctx = new Classpathxmlapplicationcontext ("Applicationcontext-aop.xml");
	        Personserver bean = (personserver) ctx.getbean ("Personservicebean");
	        Bean.save ("Badmonkey");	    	Personserver p = new Personserverimpl ();//The new object is not triggered by the AOP
//	    	P.save ("One", "a");}
}

"Run result 1":

@Around into surround notification ...
@Before Pre-notification: [Badmonkey, 23]
Come in Personserverimpl Save method ...
Com. Aspecttest.service.personserverimpl@11023cad end of operation, exit method; surround [@Around]. ...
@After post-notification ...
@AfterReturning Final Notice ... end!

"Run result 2":

@Around into surround notification ...
@Before Pre-notification: [Badmonkey, 23]
@After post-notification ...
@AfterThrowing Exception Notification (exception notification) [Badmonkey, 23]
@AfterThrowing exception Information: java.lang.ArithmeticException:/by zero

Demo Download Address: http://download.csdn.net/detail/lp1052843207/9624305



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.