声明:本站文章均为作者个人原创,图片均为实际截图。如有需要请收藏网站,禁止转载,谢谢配合!!!

AOP (Aspect Orient Programming)面向切面编程,AOP 是一种编程思想,是面向对象编程(OOP)的一种补充。实现在不修改源代码的情况下给程序动态统一添加额外功能的一种技术

  • 连接点 JoinPoint

  • 切入点 Pointcut

  • 通知 Advice

可以看到 spring-context 已经包含 aop

SpringAop教程(1)基本使用

1.导入 aspectjweaver 依赖

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
    <scope>runtime</scope>
</dependency>

2.新建 BookDao 及实现类

dao/impl/BookDaoImpl

package com.badianboke.dao.impl;

import com.badianboke.dao.BookDao;
import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements BookDao {
    @Override
    public void save() {
        System.out.println("book dao -- save");
    }
}

3.新建 MyAdvice 通知类

aop/MyAdvice

package com.badianboke.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAdvice {
    @Pointcut("execution(void com.badianboke.dao.BookDao.save())")
    private void pt(){};

    @Before("pt()")
    public void method1(){
        System.out.println("八点博客 -- before");
    }

    @After("pt()")
    public void method2(){
        System.out.println("八点博客 -- after");
    }

    @Around("pt()")
    public void method3(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("八点博客 -- around start");
        joinPoint.proceed();
        System.out.println("八点博客 -- around end");
    }

}

此外还有 @AfterReturning@AfterThrowing 方法

4.新建 SpringConfig 配置类

config/SpringConfig

package com.badianboke.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.badianboke")
@EnableAspectJAutoProxy //启用Aop自动代理
public class SpringConfig {
}

5.新建 App 启动类

App

package com.badianboke;

import com.badianboke.config.SpringConfig;
import com.badianboke.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main(String[] args){
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = ctx.getBean(BookDao.class);
        bookDao.save();
    }
}

运行结果

SpringAop教程(1)基本使用

6、切入点表达式

  • *
  • ..
  • +
@Pointcut("execution(* com..BookDao.save(..))")



点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论