spring学习笔记十六

该文章展示了如何在Spring中使用AOP进行面向切面编程,包括配置@EnableAspectJAutoProxy开启AOP支持,定义切点(@Pointcut),以及使用@Before、@After、@AfterReturning、@AfterThrowing和@Around注解实现前置、后置、返回后、异常后和环绕通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AOP面向切面编程

1、导入pom坐标

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

2、SpringConfig配置类

@Configuration
@ComponentScan("com.itheima")
@EnableAspectJAutoProxy
public class SpringConfig {

}
  • @Configuration  设置为配置类
  • @ComponentScan  扫描路径
  • @EnableAspectJAutoProxy   开启AOP切面编程

3、BookDao接口和实现类

public interface BookDao {
    void save();

    void update();
}

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

    public void update() {
        System.out.println("book update ...");
    }
}

 4、AOP类

@Component
@Aspect
public class MyAdvice {
    //@Pointcut("execution(void com.itheima.dao.BookDao.update())")


    @Pointcut("execution(void com.itheima..BookDao.update())")
    private  void pt(){}


    //前置
    @Before("pt()")
    public void before(JoinPoint jp){
        System.out.println(System.currentTimeMillis());
    }
    //  后置
    @After("pt()")
    public void after(){
        System.out.println("after .....");
    }

    //环绕  通知
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjd) throws Throwable {
        System.out.println("before around....");
        // 有返回值需要返回下
        Object ret = pjd.proceed();
        System.out.println("after around....");
        return ret;
    }

    // 执行成功后通知
    @AfterReturning(value = "pt()", returning = "ret")
    public void afterReturning(Object ret){
        System.out.println("after returning ..."+ ret);
    }



    // 抛出一场后通知
    @AfterThrowing(value = "pt()", throwing = "err")
    public void afterThrowing(Throwable err){
        System.out.println("after throwing..."+ err);
    }
}

5、使用方法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值