Spring AOP注解方式实现

简介html

上文已经提到了Spring AOP的概念以及简单的静态代理、动态代理简单示例,连接地址:https://www.cnblogs.com/chenzhaoren/p/9959596.htmlspring

本文将介绍Spring AOP的经常使用注解以及注解形式实现动态代理的简单示例。ide

经常使用注解测试

@aspect:定义切面spa

@pointcut:定义切点代理

@Before:前置通知,在方法执行以前执行code

@After:后置通知,在方法执行以后执行 component

@AfterRunning:返回通知,在方法返回结果以后执行xml

@AfterThrowing:异常通知,在方法抛出异常以后执行htm

@Around:环绕通知,围绕着方法执行

启动Spring AOP注解自动代理

1. 在 classpath 下包含 AspectJ 类库:aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar

2. 将 aop Schema 添加到 Bean 配置文件 <beans> 根元素中。

3. 在 Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy proxy-target-class="true"/>

当 Spring IOC 容器检测到 Bean配置文件中的<aop:aspectj-autoproxy proxy-target-class="true"/> 元素时,会自动为与 AspectJ 切面匹配的 Bean 建立代理。

代码示例

1. 定义被代理类接口

packege com.czr.aop.model; public interface superMan{ //自我介绍
    public void introduce(); }

2. 定义被代理类

packege com.czr.aop.model; 
@Component("superMan")
public class SuperManImpl implements SuperMan { @override public void introduce(){ System.out.println("我是内裤外穿的超人!!!"); } }

3. 定义切点类

package com.czr.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Component("annotationAop") @Aspect public class AnnotationAop { //定义切点
    @Pointcut("execution(* com.czr.aop.model.*(..))") public void pointCutName(){} @Before("pointCutName()") public void beforeAdvice(){ System.out.println("*注解前置通知实现*"); } //后置通知
    @After("pointCutName()") public void afterAdvice(){ System.out.println("*注解后置通知实现*"); } //环绕通知。ProceedingJoinPoint参数必须传入。
    @Around("pointCutName()") public void aroudAdvice(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("*注解环绕通知实现 - 环绕前*"); pjp.proceed();//执行方法
        System.out.println("*注解环绕通知实现 - 环绕后*"); } } 

4. 定义Spring文件aop.xml

<?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:tx="http://www.springframework.org/schema/tx"   xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-4.2.xsd   http://www.springframework.org/schema/aop   http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
        
    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.czr.aop,com.czr.aop.model"/>
    <!-- 开启aop注解方式 -->
    <aop:aspectj-autoproxy/>
</beans>

5. 定义测试类

package com.czr.aop; public class Test { public static void main(String[] args) { ApplicationContext ctx = 
            new ClassPathXmlApplicationContext("aop.xml"); SuperMan sm= (SuperMan)ctx.getBean("superMan"); sm.introduce(); } }

 6. 输出结果

*注解环绕通知实现 - 环绕前*
*注解前置通知实现* 我是内裤外穿的超人!!! *注解环绕通知实现 - 环绕后*
*注解后置通知实现*
相关文章
相关标签/搜索