Spring learning (24) Spring implements AOP

There are two main ways to implement AOP in Spring:
1. Based on AspectJ annotations
2. XML-based configuration
Next, we will introduce how to use these two methods to implement AOP.

1. Use annotations to implement AOP functions
Using Spring annotations, you can achieve pre-notification, post-notification, exception notification, and surround notification .
The steps to implement the AOP function are as follows:
  1. Import Jar file
  2. Configure AOP namespace
  3. Create the target object class
  4. Create a slice
  5. Configure the aspect in the configuration file
  6. Create an entry class for testing
Next we demonstrate in an example
Specific requirements are as follows:
  • Create a Java Bean such as PersonBean
  • PersonBean contains some simple business logic, such as sports related, including walking, running, climbing, playing ball, etc.
  • Output relevant log information before, during, and after the method of each movement.

Step1 : AspectJ class library under classpath:
spring-aspects.jar
aspectj.weaver.jar
aopalliance.jar

Step2: Create an interface Person
public interface Person {
    public void work();
    public void run();
    public void playBasketball();
    public void swim();
}

Step3: Define Tager Object
import org.springframework.stereotype.Component;

/**
* Created by icarus on 2016/6/13.
* Person interface implementation class
*/
@Component("personimpl1")
public class PersonImpl1 implements Person{
    public void work() {
        System.out.println("Walk!");
    }
    public void run() {
        System.out.println("Running!");
    }
    public void playBasketball() {
        System.out.println("Play basketball!");
    }
    public void swim() {
        System.out.println("游泳!");
    }
}

Step4 : Define Aspect and Advice
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component("loggingaspect")
public class  LoggingAspect {
    @Pointcut("execution(* cn.lovepi.chapter06.aop.test.PersonImpl1.*(..))")
    public void sport(){

    }

    /**
    * Log before method execution
    * @param jp join point
    */
    @Before("sport()")
    public void loggerBeforeAction(JoinPoint jp) {
        System.out.println(jp.getSignature().getName()+"execution start");

    }

    /**
    * Record log during method execution
    * @param pjp can only be used in the advice of Around
    * @throws Throwable
    */
    @Around("sport()")
    public void loggerAroundAction(ProceedingJoinPoint pjp) throws Throwable {
        pjp.proceed();//Execute the original method
        System.out.println(pjp.getSignature().getName()+"During execution...");
    }

    /**
    * Record the log after the method is executed
    * @param jp join point
    * @throws Throwable
    */
    @After("sport()")
    public void loggerAfterAction(JoinPoint jp){
        System.out.println(jp.getSignature().getName()+"execution end");

    }
}

Step5 : Make Aop settings
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--Enable annotation scanning-->
    <context:component-scan base-package="cn.lovepi.chapter06.aop.test"/>
    <!--Open Spring dynamic proxy-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

Description : AspectJ dynamic proxy support must be enabled in the Spring IoC container

Step6 : Test
public class Main {
    public static void main(String[] args){
        ApplicationContext context=
                new FileSystemXmlApplicationContext("src/conf/conf-test.xml");
        cn.lovepi.chapter06.aop.test.PersonImpl1 person=context.getBean("personimpl1",cn.lovepi.chapter06.aop.test.PersonImpl1.class);
        person.run();
        person.work();
        person.playBasketball();
        person.swim();
    }
}

Program execution result:
run execution starts
Run!
During the execution of run...
run execution ends
start of work execution
walk!
During the execution of work...
work execution ends
playBasketball execution starts
play basketball!
During the execution of playBasketball...
playBasketball execution ends
start of swim execution
Swim!
During the execution of swim...
swim execution ends


2. Use Spring XML configuration method to implement AOP function
The main steps to implement AOP are as follows:
  1. Import Jar file
  2. Configure AOP namespace
  3. Create the target object class
  4. Create a slice
  5. Configure in config file
  6. Create an entry class for testing
Next we demonstrate in an example
Specific requirements are as follows:
  • Create a Java Bean such as PersonBean
  • PersonBean contains some simple business logic, such as sports related, including walking, running, climbing, playing ball, etc.
  • Output relevant log information before, during, and after the method of each movement.

Step1 : AspectJ class library under classpath:
spring-aspects.jar
aspectj.weaver.jar
aopalliance.jar

Step2: Create an interface Person
public interface Person {
    public void work();
    public void run();
    public void playBasketball();
    public void swim();
}

Step3: Define Tager Object
public class PersonImplXml implements Person{
    public void work() {
        System.out.println("Walk!");
    }

    public void run() {
        System.out.println("Running!");
    }

    public void playBasketball() {
        System.out.println("Play basketball!");
    }

    public void swim() {
        System.out.println("游泳!");
    }
}

Step4 定义Aspect和Advice
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
* Created by icarus on 2016/6/13.
*/
public class LoggingAspectXml {
    /**
    * 开始执行方法
    * @param jp
    */
    public void loggerBeforeAction(JoinPoint jp) {
        System.out.println(jp.getSignature().getName()+"执行开始");

    }

    /**
    * 方法执行中
    * @param pjp
    * @throws Throwable
    */
    public void loggerAroundAction(ProceedingJoinPoint pjp) throws Throwable {
        pjp.proceed();//执行原方法
        System.out.println(pjp.getSignature().getName()+"执行过程中... ...");
    }

    /**
    * 方法执行结束
    * @param jp
    */
    public void loggerAfterAction(JoinPoint jp){
        System.out.println(jp.getSignature().getName()+"执行结束");

    }
}

Step5:进行Aop设置
<?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"
      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">
    <!--开启Spring动态代理-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <!--bean 配置-->
    <bean id="personImplXml" class="cn.lovepi.chapter06.aop.test.PersonImplXml"/>
    <bean id="loggingAspectXml" class="cn.lovepi.chapter06.aop.test.LoggingAspectXml"/>
    <!--aop 配置-->
    <aop:config>
        <!--设置切点-->
        <aop:pointcut id="loggingAspect" expression="execution(* cn.lovepi.chapter06.aop.test.PersonImplXml.*(..))"/>
        <!--切面设置-->
        <aop:aspect id="loggingaspect" ref="loggingAspectXml">
            <aop:before method="loggerBeforeAction" pointcut-ref="loggingAspect"/>
            <aop:around method="loggerAroundAction" pointcut-ref="loggingAspect"/>
            <aop:after method="loggerAfterAction" pointcut-ref="loggingAspect"/>
        </aop:aspect>
    </aop:config>
</beans>

说明:必须在Spring IoC容器中启用AspectJ动态代理支持

Step6:测试
public class MainXml {
    public static void main(String[] args){
        ApplicationContext context=new FileSystemXmlApplicationContext("src/conf/conf-test-xml.xml");
        PersonImplXml person=context.getBean("personImplXml",PersonImplXml.class);
        person.work();
        person.run();
        person.playBasketball();
        person.swim();
    }
}

程序执行结果:
run执行开始
跑步!
run执行过程中... ...
run执行结束
work执行开始
散步!
work执行过程中... ...
work执行结束
playBasketball执行开始
打篮球!
playBasketball执行过程中... ...
playBasketball执行结束
swim执行开始
游泳!
swim执行过程中... ...
swim执行结束

总结
通过最后结果相比较而言,AspectJ更值得推荐

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727811&siteId=291194637