Spring的AOP

一、实现自己的AOP

在之前一篇随笔中已经详细讲解了java的动态代理机制,我们也知道了AOP的底层其实就是基于动态代理机制实现的,所以这里先自己实现一下AOP

复制代码
public class DynamicProxy implements InvocationHandler
{
    // 要代理的对象
    private Object target;

    // 将构造方法禁用掉,不让外部通过new来得到DynamicProxy对象
    private DynamicProxy()
    {
    };

    /**
     * 返回一个动态的代理对象
     * 
     * @param object
     * @return
     */
    public static Object newInstance(Object object)
    {
        DynamicProxy proxy = new DynamicProxy();
        proxy.target = object;
        //    通过Proxy的newProxyInstance方法来得到一个代理对象
        Object result = Proxy.newProxyInstance(object.getClass()
                .getClassLoader(), object.getClass().getInterfaces(), proxy);
        return result;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable
    {
//        //    只有方法名为add和delete时候才引入日志
//        if(method.getName().equals("add") || method.getName().equals("delete"))
//        {
//            Logger.logInfo("动态代理类");
//        }
        
        // 根据LogAnnotation来判断,如果被标注了注解,则输出日志
        if(method.isAnnotationPresent(LogAnnotation.class))
        {
            LogAnnotation log = method.getAnnotation(LogAnnotation.class);
            Logger.logInfo(log.value());
        }
        
        Object object = method.invoke(target, args);
        return object;
    }
}
复制代码

就如上篇随笔所说,动态代理类必须要实现InvocationHandler的这个接口,我们的这个类当然也要实现这个接口了。然后在里面定义了一个私有的Object属性,表示我们要代理的对象。这里我们将这个类的构造方法禁用掉,使其不能通过外部直接new出来一个对象,然后我们写一个newInstance的方法来给我们的代理对象赋初值,并且返回的就是我们的代理对象。我们看看在beans.xml中的配置文件

<!-- 如果要对static方法进行注入,可以通过factory-method属性来制定方法名字,并通过构造函数的方式传入参数 -->
        <bean id="userDAOProxy" class="com.xiaoluo.proxy.DynamicProxy" factory-method="newInstance">
            <constructor-arg ref="userDAO"/>
        </bean>

因为我们的DynamicProxy类的对象以及代理对象是通过static方法来进行注入的,因此我们如果要对其进行注入的话,需要通过 factory-method 这个属性来给我们的静态方法进行属性注入,通过 <constructor-arg>来讲参数传递进去,这样我们的userDAOProxy就是一个代理对象了。

二、通过Annotation来配置我们的AOP

我们要将AOP的schema引入,如果使用注解的话,还要开启AOP的自动代理

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
        
        <!-- 通过annotation来进行bean的创建 -->
        <context:annotation-config/>
        <!-- 对以com.xiaoluo开头的包进行扫描 -->
        <context:component-scan base-package="com.xiaoluo"/>
        <!-- 开启AOP的自动代理,只要加入了@Aspect标签就自动代理 -->
        <aop:aspectj-autoproxy/>
        
</beans>
复制代码

然后我们来看看我们的切面类:

复制代码
@Component("logAspect")    //    将该切面类由Spring托管
@Aspect    //    声明该类是一个Aspect,切面类
public class LogAspect
{
    /**
     * execution(* com.xiaoluo.dao.*.add*(..))
     * 第一个*表示任意返回值
     * 第二个*表示com.xiaoluo.dao下的所有类
     * 第三个*表示所有以add开头的方法
     * (..)表示方法接收的任何参数
     */
    /*
     * Before在方法执行前执行
     */
    @Before("execution(* com.xiaoluo.dao.*.add*(..))||" +
            "execution(* com.xiaoluo.dao.*.delete*(..))||" +
            "execution(* com.xiaoluo.dao.*.update*(..))")
    public void logStart(JoinPoint jp)
    {
        //    得到该JoinPoint的类
        System.out.println(jp.getTarget());
        //    得到该JoinPoint的方法
        System.out.println(jp.getSignature());
        //    得到该JoinPoint的方法的名字
        System.out.println(jp.getSignature().getName());
        Logger.logInfo("日志开始");
    }
    
    /*
     * After在方法执行只会执行
     */
    @After("execution(* com.xiaoluo.dao.*.add*(..))||" +
            "execution(* com.xiaoluo.dao.*.delete*(..))||" +
            "execution(* com.xiaoluo.dao.*.update*(..))")
    public void logEnd()
    {
        Logger.logInfo("日志结束");
    }
    
    /*
     * Around包含了这个方法的执行
     * 
     * Logger.logInfo("开始执行Around日志");
     * pjp.proceed();
     * Logger.logInfo("结束了Around日志");的执行顺序为:
     * 
     * 首先执行 Logger.logInfo("开始执行Around日志");,接着执行方法,因为在方法执行要执行
     * Before,所以先执行完Before再执行方法,接着执行  Logger.logInfo("结束了Around日志");
     * 最后执行After
     * 
     */
    @Around("execution(* com.xiaoluo.dao.*.add*(..))||" +
            "execution(* com.xiaoluo.dao.*.delete*(..))||" +
            "execution(* com.xiaoluo.dao.*.update*(..))")
    public void logAround(ProceedingJoinPoint pjp) throws Throwable
    {
        Logger.logInfo("开始执行Around日志");
        pjp.proceed();
        Logger.logInfo("结束了Around日志");
    }
}
复制代码

因为Spring的AOP使用的是第三方的jar包,所以我们这里还要引入三个AOP的jar文件:

aopalliance-1.0.jar
aspectjrt-1.7.3.jar
aspectjweaver-1.7.3.jar

这样我们的基于注解的AOP就配置好可以使用了。

三、基于XML的AOP配置

如果基于XML的AOP配置,我们的beans.xml配置如下

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
        
        <!-- 通过annotation来进行bean的创建 -->
        <context:annotation-config/>
        <!-- 对以com.xiaoluo开头的包进行扫描 -->
        <context:component-scan base-package="com.xiaoluo"/>
        <!-- 通过xml方式来配置AOP -->
        <aop:config>
            <!-- 声明一个切面 -->
            <aop:aspect id="myLogAspect" ref="logAspect">
                <!-- 声明在哪些位置我要加入这个切面 -->
                <aop:pointcut id="logPoint" expression="execution(* com.xiaoluo.dao.*.add*(..))||
                                                        execution(* com.xiaoluo.dao.*.delete*(..))||
                                                        execution(* com.xiaoluo.dao.*.update*(..))"/>
                <aop:before method="logStart" pointcut-ref="logPoint"/>
                <aop:after method="logEnd" pointcut-ref="logPoint"/>
                <aop:around method="logAround" pointcut-ref="logPoint"/>                
            </aop:aspect>
        </aop:config>        
</beans>
复制代码

我们这里当然也要声明我们的切面类:

复制代码
@Component("logAspect")    //    将该切面类由Spring托管
public class LogAspect
{
    public void logStart(JoinPoint jp)
    {
        //    得到该JoinPoint的类
        System.out.println(jp.getTarget());
        //    得到该JoinPoint的方法
        System.out.println(jp.getSignature());
        //    得到该JoinPoint的方法的名字
        System.out.println(jp.getSignature().getName());
        Logger.logInfo("日志开始");
    }
    
    public void logEnd()
    {
        Logger.logInfo("日志结束");
    }
    
    public void logAround(ProceedingJoinPoint pjp) throws Throwable
    {
        Logger.logInfo("开始执行Around日志");
        pjp.proceed();
        Logger.logInfo("结束了Around日志");
    }
}
复制代码

本篇随笔主要记录了自己实现AOP的配置以及基于Annotation和XML的方式来配置我们的AOP

###Spring AOP 的概念 AOP(Aspect-Oriented Programming)即面向切面编程,是一种编程范式,旨在通过分离横切关注点来提高模块化程度。在 Spring 框架中,AOP 被广泛用于实现诸如日志记录、事务管理、安全性等通用功能,这些功能通常与业务逻辑无关但又需要在多个地方重复使用。 Spring AOP 主要是基于 AspectJ 实现的,尽管 AspectJ 是一个独立的 AOP 框架,并不是 Spring 的组成部分,但它通常与 Spring 一起使用以提供更强大的 AOP 功能[^1]。Spring AOP 支持两种方式来定义切面:基于 XML 配置文件的方式和基于注解的方式。 ###Spring AOP 的原理 Spring AOP 使用运行时代理来实现 AOP 功能,这意味着它会在运行时动态生成代理对象。对于实现了接口的类,Spring AOP 默认使用 JDK 动态代理;而对于没有实现接口的类,则会使用 CGLIB 代理[^4]。这种方式允许在不修改原始代码的情况下向程序中添加新的行为。 织入(Weaving)是将增强(advice)应用到目标对象的过程,Spring AOP 在运行时进行织入操作[^3]。当创建了代理对象后,所有对目标对象方法的调用都会被拦截,并且可以插入额外的操作,比如在方法执行前后做一些处理。 ###Spring AOP 的使用教程 要开始使用 Spring AOP,首先需要确保项目中包含了必要的依赖。如果使用 Maven 构建工具,可以在 `pom.xml` 文件中加入如下依赖: ```xml <!-- 引入aop依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 一旦添加了依赖并刷新了 Maven 项目,就可以开始编写切面了。下面是一个简单的例子,展示如何使用注解来定义一个切面: ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Method " + joinPoint.getSignature().getName() + " is called."); } } ``` 在这个示例中,`LoggingAspect` 类被标记为 `@Aspect` 和 `@Component` 注解,这样 Spring 就能识别这是一个切面组件。`@Before` 注解指定了在哪些方法上应用前置通知(before advice),这里的表达式表示匹配 `com.example.service` 包下所有的方法。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值