spring-Aop by aspectj 注解(1) 入门体验

spring-Aop 1.2(1) aspectj体验

一、 spring aop实现方式之一:aspectj aop基本实现test

1. 定义接口:

package com.msyd.spring.aop.aspectj;
public interface Performer {
    public void perform();
}

2. 目标对象类:

package com.msyd.spring.aop.aspectj;
public class Singer implements Performer {
    public void perform() {
        System.out.println("action:i am a singer!i speak for myself ! ");
    }
}

3. 切面类中定义通知:

@Aspect
public class Audience {
    /**
     * aspectj表达式:切入点表达式,第一颗星代表任意返回值,后面( com.msyd.spring.aop.aspectj.Performer)是要代理的接口以及要加通知的方法(perform())
     * */
    @Before(""execution(* com.msyd.spring.aop.aspectj.Performer.perform())"")
    public void takeSeat() {
        System.out.println("all audiences sit Down ");
    }

4. 配置文件aspectj.xml

<?xml version="1.0"?>
<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/aop
     http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

      <bean class="com.msyd.spring.aop.aspectj.Audience"/>

      <bean id="singer" class="com.msyd.spring.aop.aspectj.Singer"/> 

      <!-- aop自动代理 -->
      <aop:aspectj-autoproxy />
</beans>

5. 测试类:App.class

package com.msyd.spring.aop.aspectj;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("aspectj.xml", App.class);
        Performer P = (Performer) ac.getBean("singer");//获取目标对象,自动代理可以用接口来接收
        P.perform();
    }
}

前置通知结果:

all audiences sit Down
action:i am a singer!i speak for myself ! 

二、通知调用步骤:

回顾之前aop体验里,各种通知方式对应的接口分别为:
- 前置通知:MethodBeforeAdvice,不能阻止调用目标方法。
- 后置通知:AfterReturningAdvice.没有返回值
- 环绕通知:MethodInterceptor 方法拦截器
- Throws异常:ThrowableAdvice. 里面没有方法,标识性接口.// eg:java.io.serializable串行化接口也是标识性接口。

aspectj 讲述 通过aspectj方式实现aop开发,步骤如下:


  1. 关键类库:aspectjrt.jar ,aspectjweaver.jar
  2. 添加aop schema:接口类和目标对象类.
  3. 编写切面java类,并在类上加@aspect注解
  4. 定义xml元素:切面,目标对象,以及<aop:aspectj-autoproxy> (取自aop3.1.xsd) jdk1.7
  5. 测试,over。


附:第3点追加描述:
下面注解是在切面类里编辑,加在不同的通知方法上,在代理方法调用时,会根据注解先后调用通知。aspectj支持5种类型的通知注解,本文只体验了下前置通知,整合后的通知可以参看博文:spring-Aop 1.2 aspectj(2)入门体验,具体test下面注解通知的形式
①. @before:前置通知,在方法执行之前执行
②. @after:后置通知,在方法执行之后执行
③. @afterReturning:返回通知,在方法返回结果之后执行
④. @afterThrowing:异常通知,在方法抛出异常之后执行
⑤. @around:环绕通知,围绕着方法执行
在上面注解里加上切入点表达式,eg:execution(* proxyInterface.methodName()):

猜你喜欢

转载自blog.csdn.net/haidaoxianzi/article/details/80382289