Spring-AOP看这个

2 篇文章 0 订阅
1 篇文章 0 订阅
文章介绍了Spring框架中的两个核心概念——IOC(控制反转)和AOP(面向切面编程)。对于IOC,讲解了如何通过XML配置将对象的管理交给Spring容器。而对于AOP,阐述了其用于功能增强和减少代码重复的作用,以及如何定义切面、编写环绕通知并应用到实际方法中。
摘要由CSDN通过智能技术生成

二、AOP

AOP作用:在不改变原始设计的基础上为其进行功能增强, 将不同类的不同方法抽象成一个切面,自动注入执行,减少系统的重复代码,降低模块间的耦合度。
应用场景:安全校验、日志操作、事务操作,缓存,权限、调试,错误处理,同步,持久化数据等等

1.在pom.xml中导入Spring和aspect坐标

<!--        第1步。导入坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

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

2.定义对象,声明业务接口,以及实现方法

在这里插入图片描述

3.添加Aop配置类的逻辑

package com.guoc.config;

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

//@Aspect是将该类声明为切面类,再加@Component 进行Spring管理
@Aspect
@Component
public class AopConfig {

    @Pointcut("execution(* com.guoc.dao.bookdao.*(..))")
    public void pt(){}

   /* @After("pt()")
    public void afterMethod(){
        System.out.println("after");
    }

    @Before("pt()")
    public void beforeMethod(){
        System.out.println("before");
    }*/

    @Around("pt()")
    public Object aroundMethod(ProceedingJoinPoint pjt) throws Throwable {
        System.out.println("环绕前");
        //若目标方法有返回值,则该方法的返回值就是目标方法的返回值。
        Object rtn = pjt.proceed();
        System.out.println("环绕后");

        System.out.println(rtn.toString());

       return rtn;

    }

}

输出结果
环绕前
老人与海
环绕后
老人与海

4.添加Spring配置类,开启注解驱动支持

在这里插入图片描述

5.获取Bean调用

package com.guoc;

import com.guoc.config.SpringConfig;
import com.guoc.dao.bookdao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AOPMain {
    public static void main(String[] args) {

        //读取上下文空间
        ApplicationContext ctx= new AnnotationConfigApplicationContext(SpringConfig.class);

        //获取bean
        bookdao book=ctx.getBean(bookdao.class);

        book.getBook();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值