AOP简介

目录

AOP简介

AOP思想的实现方案

模拟AOP的基础代码

AOP相关概念


AOP简介

AOP,Aspect Oriented Programming,面向切面编程,是对面向编程OOP的升华。OOP是纵向对一个事物的抽象,一个对象包括静态的属性信息,包括动态的方法信息等。而AOP是横向的对不同事物的抽象,属性与属性,方法与方法,对象与对象都可以组成一个切面,用这种思维去设计编程的方式叫做面向切面编程

AOP思想的实现方案

动态代理技术,在运行期间,对目标对象的方法进行增强,代理对象同名方法内可以执行原有逻辑的同时,嵌入执行其他增强逻辑或其他对象的方法

模拟AOP的基础代码

debug中获取某个特定值

java 复制代码
public class MockBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
        //对UserServiceImpl实现增强,增强方法在MyAdvice中
        //问题对Bean进行筛选service.Impl包下的所有类的所有方法都可以进行增强,
        // MyAdvice的获取     从Spring容器中获取
        if (bean.getClass().getPackage().getName().equals("com.hsf.service.Impl")){
            //为UserService创建代理
            Object BeanProxy=Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),//类加载器
                    bean.getClass().getInterfaces(),//类实现的接口
                    (Object proxy, Method method, Object[] args) -> {
                        //获取增强对象
                        MyAdvice myAdvice = applicationContext.getBean(MyAdvice.class);
                        //执行增强对象A方法
                        myAdvice.beforeAdvice();
                        //执行目标对象方法
                        Object invoke = method.invoke(bean, args);
                        //执行增强对象b方法
                        myAdvice.afterAdvice();
                        return invoke;
                    }

            );
            return BeanProxy;
        }
        return bean;

    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}

原因:getBean方法 第二个参数应该写的是接口,而不是它的实现类 (动态代理的是接口【记住使用框架都要用接口类型来引用实现类对象】)

AOP相关概念
相关推荐
后端小张3 小时前
【JAVA进阶】Spring Boot 核心知识点之自动配置:原理与实战
java·开发语言·spring boot·后端·spring·spring cloud·自动配置
tg-zm8899968 小时前
2025返利商城源码/挂机自动收益可二开多语言/自定义返利比例/三级分销理财商城
java·mysql·php·laravel·1024程序员节
X***C8628 小时前
SpringBoot:几种常用的接口日期格式化方法
java·spring boot·后端
前端达人8 小时前
你的App消息推送为什么石沉大海?看Service Worker源码我终于懂了
java·开发语言
小光学长8 小时前
基于ssm的宠物交易系统的设计与实现850mb48h(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·前端·数据库
编程大师哥9 小时前
vxe-table 透视表分组汇总及排序基础配置
java
8***84829 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
9***J6289 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
M***Z2109 小时前
SQL 建表语句详解
java·数据库·sql
v***7949 小时前
Spring Boot 热部署
java·spring boot·后端