Wu Yuxiong - a natural framework for the development of natural JAVA SPRING study notes: Spring uses the AspectJ AOP XML-based and development-based Annotation

AspectJ is a Java-based AOP framework that extends the Java language. Spring 2.0 later added support for AspectJ way, the new version of the Spring Framework, recommended way to develop AspectJ AOP. 
Using AspectJ AOP usually develop in two ways: 
based on declarative XML. 
Annotation-based declarative.
XML-based declarative 
XML-based declarative Spring configuration file refers to the way the definition section, the starting point and declare notice, and all aspect and advisor must be defined in <aop: config> element. 
Here how to use development to achieve AOP XML-based declarative through case presentation in Spring. 
1 . Import JAR package 
used in addition to the introduction Spring AOP AspectJ JAR packages required beyond those associated with the introduction of the AspectJ JAR package, as follows. 
Spring -aspects-3.2.13 .RELEASE.jar: Spring implemented to provide AspectJ has been provided in the Spring package. 
com.springsource.org.aspectj.weaver -1.6.8.RELEASE.jar: AspectJ is provided specifications, the official website can https: // repo.spring.io/webapp/#/search/quick/ search for and download . 
2 . Create a class MyAspect cut 
to create a package called com.mengma.aspectj.xml in src directory, creating class MyAspect cut in the packet, as shown below after editing. 
Package com.mengma.aspectj.xml;
 Import org.aspectj.lang.JoinPoint;
Import org.aspectj.lang.ProceedingJoinPoint;
 // aspect class 
public  class MyAspect {
     // pre-notification 
    public  void myBefore (the JoinPoint Joinpoint) { 
        of System.out.print ( "pre-notification, the target:" ); 
        the System.out. Print (joinPoint.getTarget () + "method name:" ); 
        System.out.println (joinPoint.getSignature () getName ().); 
    } 
    // post notifications 
    public  void myAfterReturning (the JoinPoint Joinpoint) { 
        the System.out. Print ( "post-notification method name:" + joinPoint.getSignature () getName ().); 
    } 
    // around advice
    public Object myAround (ProceedingJoinPoint ProceedingJoinPoint)
             throws the Throwable { 
        System.out.println ( "Surround Start"); // start 
        Object obj = proceedingJoinPoint.proceed (); // implementation of the current target method 
        System.out.println ( "Surround End" ); // end 
        return obj; 
    } 
    // abnormality notification 
    public  void myAfterThrowing (the JoinPoint Joinpoint, the Throwable E) { 
        System.out.println ( "abnormality notification" + "wrong" + e.getMessage ()); 
    } 
    // The final notification 
    public  void myAfter () { 
        System.out.println ( "final notice" ); 
    } 
} 
the above code, respectively, define different types of notification methods, these methods can be obtained by the class name of the target object parameter JoinPoint target method name and destination methods parameters. Note that, receiving a notice must surround parameter ProceedingJoinPoint type, the return value must be of type Object, and must throw an exception. Throwable abnormality notification may be passed types of parameters, for outputting the abnormality information. 
3 . Creating a Spring configuration file 
created in the profile applicationContext.xml com.mengma.aspectj.xml package, as follows. 
<? XML Version = "1.0" encoding = "UTF-. 8"?> 
<Beans xmlns = "http://www.springframework.org/schema/beans" 
    xmlns: the xsi = "http://www.w3.org / 2001 / XMLSchema-instance "xmlns: AOP =" http://www.springframework.org/schema/aop " 
    xsi: schemaLocation ="   
            HTTP: // www.springframework.// www.springframework.org/schema/beans/spring-beans-2.5.xsd   
            HTTP: // www.springframework.org/schema/aop 
            HTTP: // www.springframework.org/schema/aop/spring-aop- 2.5.xsd "> 
    <-! target class -> 
    <the bean ID =" customerDao " class =" com.mengma.dao.CustomerDaoImpl "/> 
    <-! aspect class -> 
    <the bean ID =" myAspect " class = "com.mengma.aspectj.xml.MyAspect"> </ the bean> 
    <- programming the AOP ->! 
    <AOP: config> 
        <AOP: Aspect REF = "myAspect"> 
            ! <- configuration entry point, which method to enhance the final notice -> 
            <AOP:pointcut expression="execution ( * com.mengma.dao.*.* (..))"
                id= "myPointCut" /> 
            ! <- pre-notification, the notification associated with an entry point and Advice PointCut -> 
            <AOP: before Method = "myBefore" pointeut-REF = "myPointCut" /> 
            <- after advice,! after performing the method returns, the return value can be obtained returning attribute -> 
            <AOP: after returning-method = "myAfterReturning" 
                the pointcut -REF = "myPointCut" returning = "returnVal" /> 
            <- surround notification ->! 
            <AOP: around method = "myAround" the pointcut-REF = "myPointCut" /> 
            <-! Throws notification: for exception handler occurs, can receive the abnormal current method produces -> 
            <- * Note!: If the program is not an exception, it will not perform an enhanced -> 
            <- * throwing attributes:! the name of the second parameter set notifications, the type Throwable ->
            <aop:after-throwing method="myAfterThrowing"
                pointcut= -ref "myPointCut" throwing = "E" /> 
            ! <- final notification: Whatever happens, happens regardless of the program, will be executed -> 
            <AOP: Method, the After = "myAfter" pointcut-ref = "myPointCut" /> 
        </ AOP: Aspect> 
    </ AOP: config> 
</ Beans> 
in the above code, the first of 4,7,8 lines of code were introduced into the namespace AOP. 12th line specifies the class section. 
The first 17 and 18 are configured starting point line, which methods require notification enhancement, expression = "execution (* com.mengma.dao . *. * (..)) means that all the reinforcement package com.mengma.dao a method 
of 20 to 32 lines of code associated with a notification (the Advice) and the starting point (pointCut) code prefix, line 20 to notify an example, <aop: before>. method property specifies a notification tag, pointcut- REF property specifies the starting point, that is, to enhance the process, notification may be arranged several other reference code comments.
 4 creating a test class 
to create a test class XMLTest at com.mengma.aspectj.xml package, as follows. 
package com.mengma.
 org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mengma.dao.CustomerDao;
public class XMLTest {
    @Test
    public void test() {
        String xmlPath = "com/mengma/aspectj/xml/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        // 从spring容器获取实例
        CustomerDao customerDao = (CustomerDao) applicationContext
                .getBean ( "customerDao");
         // execution method 
        customerDao.add (); 
    } 
}
 5 . Run the project and view the results 
using the JUnit test run test () method, after a successful run, the console output

 

 

Annotation declarative based 
in Spring, despite the use of XML configuration files can be developed to achieve AOP, but if all configurations are concentrated in the configuration file, will inevitably lead to an XML configuration file is too bloated, and thus to bring some maintenance and upgrades Difficulties. 
To this end, AspectJ framework provides another way for the development of AOP development - Annotation-based declarative. AspectJ allows using the annotated section, starting point, and enhancement processing, and the frame can be identified and Spring AOP agent according to generate these annotations. 
About Annotation annotation 
@Aspect used to define a section. 
It is used to define pre-notification @Before corresponds BeforeAdvice. 
@AfterReturning for defining post-notification corresponds AfterReturningAdvice. 
@Around for defining around advice, corresponding to MethodInterceptor. 
@AfterThrowing used to define thrown notice, the equivalent of ThrowAdvice. 
@After used to define the final final notice, regardless of whether or not an exception, the notice will be executed. 
@DeclareParents for defining introduce notification, an IntroductionInterceptor is equivalent (not required to master).
1 . Create a class MyAspect cut 
to create a package called com.mengma.aspectj.annotation in src directory, create a class MyAspect cut at the packet, as shown below. 
Package com.mengma.aspectj.annotation;
 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;
 Importorg.springframework.stereotype.Component;
 // aspect class 
@Aspect 
@Component 
public  class MyAspect {
     // for substitution: <AOP: the pointcut
     // expression The = "Execution (com.mengma.dao .. * * * (.. .)) "ID =" myPointCut "/>
     // requirements: The method must be private, no value, the name of the custom, no parameters 
    @Pointcut (" execution (* com.mengma.dao .. * * (...) ) " )
     Private  void myPointCut () { 
    } 
    // pre-notification 
    @Before (" myPointCut () " )
     public  void myBefore (the JoinPoint Joinpoint) { 
        of System.out.print ( " pre-notification, the target: " );
        System.out.print(joinPoint.getTarget() + "方法名称:");
        System.out.println(joinPoint.getSignature().getName());
    }
    // 后置通知
    @AfterReturning(value = "myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint) {
        System.out.print("后置通知,方法名称:" + joinPoint.getSignature().getName());
    }
    // 环绕通知
    @Around("myPointCut()")
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint)
            throws Throwable {
        System.out.println("环绕开始");start//
        = ProceedingJoinPoint.proceed obj Object (); // implementation of the current target method 
        System.out.println ( "Surround End"); // End 
        return obj; 
    } 
    // abnormality notification 
    @AfterThrowing (value = "myPointCut () ", throwing = "E" )
     public  void myAfterThrowing (the JoinPoint Joinpoint, the Throwable E) { 
        System.out.println ( "abnormality notification" + "wrong" + e.getMessage ()); 
    } 
    // final notification 
    @After ( "myPointCut ( ) " )
     public  void myAfter () { 
        System.out.println ( " final notice " );
    } 
}
The above code, the first 13 rows @Aspect Annotations for this section is a class that is used as a component, so to add a comment @Component to take effect. 19, line @Poincut annotation entry point for configuring, substituted configured in the code entry points XML file. 

Each notice on the appropriate methods to add a comment statement, and the entry point method name "myPointCut" passed to the method to be executed as an argument for additional parameters (such as notification of abnormal abnormal parameters), can be passed in accordance with the code hints the corresponding property value. 
2 . Annotate the target class 
annotate @Repository (in com.mengma.dao.CustomerDaoImpl target class "customerDao" ).
3 . Creating a Spring configuration file 
created in com.mengma.aspectj.annotation applicationContext.xml profile package, as shown below. 
<? XML Version = "1.0" encoding = "UTF-. 8"?> 
<Beans xmlns = "http://www.springframework.org/schema/beans" 
    xmlns: the xsi = "http://www.w3.org / 2001 / XMLSchema-instance " 
    xmlns: AOP =" http://www.springframework.org/schema/aop "= "http://www.springframework.org/schema/context" 
    xsi: schemaLocation = "http://www.springframework.org/schema/beans 
            HTTP: // www.springframework.org/schema/beans/spring- 2.5.xsd-Beans 
            HTTP: // www.springframework.org/schema/aop 
            HTTP: // www.springframework.org/schema/aop/spring-aop-2.5.xsd 
            HTTP: // www.springframework.org/schema / context 
            HTTP: // www.springframework.org/schema/context/spring-context.xsd "> 
    <- scan with all annotations in com.mengma bag ->! 
    <context: the Component-scan base- package Penalty for = "com.mengma" /> 
    < ! - cut open the automatic proxy -> 
    <AOP: AspectJ-the autoproxy> </ AOP: AspectJ-the autoproxy> 
</ Beans> 
above code, first introduced AOP namespace constraints and supporting the cut class the annotation is working @AspectJ; first line of code adds scan package 13, so that the annotation effect. Note that, here, further comprising annotation com.mengma.dao.CustomerDaoImpl target class, so base- Package value com.mengma; 15, action lines are cut automatically turned agent.
4 creating a test class 
to create a test class named AnnotationTest at com.mengma.aspectj.annotation package, as follows. 
Package com.mengma.aspectj.annotation;
 Import org.junit.Test;
 Import org.springframework.context.ApplicationContext;
 Import org.springframework.context.support.ClassPathXmlApplicationContext;
 Import com.mengma.dao.CustomerDao;
 public class{AnnotationTest 
    @Test 
    public  void Test () { 
        String XMLPath = "COM / mengma / AspectJ / XML / the applicationContext.xml" ; 
        the ApplicationContext applicationContext = new new the ClassPathXmlApplicationContext ( 
                XMLPath); 
        // Get instance from spring containers 
        CustomerDao customerDao = (CustomerDao) applicationContext 
                .getBean ( "customerDao" );
         // execution method 
        customerDao.add (); 
    } 
}
 5 . run the project and view the results 
using the JUnit test after test run () method, run successfully, the console output

 

Guess you like

Origin www.cnblogs.com/tszr/p/12150309.html