04 注解方式完成aop
发布日期:2022-03-30 20:19:33 浏览次数:25 分类:博客文章

本文共 2574 字,大约阅读时间需要 8 分钟。

前面几节我们使用三种方式完成了代理,接下来,我们将看一下在spring中如何完成aop。

1、前提约束

  • 完成基于注解的springmvc的demo

2、操作步骤

  • 在src/main/resources文件夹下创建一个application-aop-anno.xml,内容如下:
  • 在src/main/java文件夹下创建net.wanho.aspect.MyAspect.java,内容如下:
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;import java.util.Arrays;@Aspect@Componentpublic class MyAspect {    @Pointcut("execution(* net.wanho.aspect.StudentService.*())")    public void pointCut(){}    @After("pointCut()")    public void testPointcut()    {        System.out.println("testPointcut");    }    @Before("execution(* net.wanho.aspect.StudentService.*(..))")    public void security(JoinPoint joinPoint)    {        System.out.println(joinPoint.getKind()+"."+joinPoint.getSignature().getName()+":("+Arrays.toString(joinPoint.getArgs())+")");        System.out.println("权限");    }    @Around("execution(* net.wanho.aspect.StudentService.*(int)))")    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {        System.out.println("around in");        Object object = proceedingJoinPoint.proceed();        System.out.println("around out");        return object;    }    @AfterThrowing("execution(* net.wanho.aspect.StudentService.*(int)))")    public void afterThrowing()    {        System.out.println("exception");    }    @AfterReturning("execution(* net.wanho.aspect.StudentService.*(int)))")    public void afterReturning()    {        System.out.println("return");    }}
  • 在src/main/java文件夹下创建net.wanho.aspect.StudentService.java
public interface StudentService {    void query();}
  • 在src/main/java文件夹下创建net.wanho.aspect.StudentServiceImpl.java
import net.wanho.class134.entity.Student;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Map;@Component(value = "studentService")public class StudentServiceImpl implements StudentService {    @Override    public void query() {        System.out.println("查询");    }}
  • 在src/main/java文件夹下创建net.wanho.aspect.Test.java
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {    public static void main(String[] args) throws Exception {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-aop-anno.xml");        StudentService studentService = applicationContext.getBean("studentService", StudentService.class);        studentService.query();    }}

以上就是采用注解方式完成aop的过程。

转载地址:https://www.cnblogs.com/alichengxuyuan/p/12554684.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:03 cglib动态代理
下一篇:13 springmvc完成文件上传

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月20日 17时25分57秒