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相关概念
相关推荐
idealzouhu5 分钟前
Java 并发编程 —— AQS 抽象队列同步器
java·开发语言
听封9 分钟前
Thymeleaf 的创建
java·spring boot·spring·maven
写bug写bug15 分钟前
6 种服务限流的实现方式
java·后端·微服务
楠枬27 分钟前
双指针算法
java·算法·leetcode
奔驰的小野码32 分钟前
java通过org.eclipse.milo实现OPCUA客户端进行连接和订阅
java·开发语言
huapiaoy34 分钟前
Spring mvc
java·spring·mvc
风控牛43 分钟前
【chromedriver编译-绕过selenium机器人检测】
java·python·selenium·测试工具·安全·机器人·行为验证
小川_wenxun1 小时前
优先级队列(堆)
java·开发语言·算法
前端专业写bug1 小时前
jspdf踩坑 htmltocanvas
java·前端·javascript