Spring基础:对AOP的理解及简单实现AOP

一、对AOP的理解
AOP,全称Aspect Oriented Programming,中文翻译来为面向切面编程通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术,它是OOP(面向对象编程)的延续,是spring框架中的一个重要内容。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性维护性,同时提高了开发的效率。
在这里插入图片描述
AOP是一个概念性的名词,真的很难去理解。在网上看了很多对AOP的阐述,可是理解起来依然摸棱两可。说的再多,还不如用简单的示例去练习再加以理解,我相信这样的效果会很不错。

二、用简单例子实现SpringAOP
1.用常用的业务类理解SpringAOP
首先编写业务类接口

package com.muzili.service;

public interface UserService {
    void add();
    void delete();
    void update();
    void query();
}

编写实现接口类

package com.muzili.service;

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("增加了一个用户");
    }

    @Override
    public void delete() {
        System.out.println("减少了一个用户");
    }

    @Override
    public void update() {
        System.out.println("更新了一个用户");
    }

    @Override
    public void query() {
        System.out.println("查询了一个用户");
    }
}

定义日志(定义两篇切入,一前一后)

package com.muzili.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

package com.muzili.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice{
    //returnValue : 返回值
    //method : 被调用的方法
    //args : 被调用的方法对象的参数
    //target : 被调用的目标对象
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+target.getClass().getName()
                +"的"+method.getName()+"方法"
                +"返回值"+returnValue);

    }
}

编写Spring的配置文件(我这里起名为applicationContext.xml,配置文件是最核心的部分,理解它是理解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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--注册bean-->
<bean id="userService" class="com.muzili.service.UserServiceImpl"/>

<!--注册日志类的bean-->
<bean id="log" class="com.muzili.log.Log"/>
<bean id="afterLog" class="com.muzili.log.AfterLog"/>

<!--使用spring的aop切入-->

<aop:config>
    <!--切入点
    expression 表达式,表示要切入的位置
    语法:execution([类的修饰符] [类的全路径] [方法] [参数])
    -->
    <aop:pointcut id="pointcut" expression
            ="execution(* com.muzili.service.UserServiceImpl.*(..))"/>
    <!--执行通知,增强-->
    <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
    <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

</aop:config>


</beans>

编写工作已经做好了,下面可以进行测试了。
测试前,需要导入一个AOP的织入包放在pom.xml(再IDEA中用maven创建项目)文件中

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

这不是最新版的包,如果需要,也可以去官网https://mvnrepository.com/artifact/org.aspectj/aspectjweaver
下载最新的。

下面可以编写测试类进行测试了

package com.muzili.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAopTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = (UserService) context.getBean("userService");
        userService.delete();

    }

点击运行后,出现以下界面
在这里插入图片描述

这里在方法的前后增加了我们要切入的日志代码,这样就实现了即调用了对象,又增加了日志功能。当然在实际业务中,你可以调用其他的功能,比如安全检查,事务管理等。

2.自定义类实现AOP
业务类和上面的一样
增加一个AOP增加类(也就是所谓的切面),替代上面的日志。

package com.muzili.diy;

public class Diy {
    public void before(){
        System.out.println("===方法执行前===");
    }
    public void after(){
        System.out.println("===方法执行后===");
    }
}

然后是编写Spring的核心配置文件,这里我起名为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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.muzili.service.UserServiceImpl"/>

    <bean id="diy" class="com.muzili.diy.Diy"/>

    <aop:config>

        <!--切面-->
        <aop:aspect ref="diy">

            <!--切入点-->
            <aop:pointcut id="diyPointCut" expression="execution(* com.muzili.service.UserServiceImpl.*(..))"/>
            <aop:before method="before" pointcut-ref="diyPointCut"/>
            <aop:after method="after" pointcut-ref="diyPointCut"/>
        </aop:aspect>
    </aop:config>
</beans>

测试

package com.muzili.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringAopTest {
    @Test
    public void test2(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.add();
    }

运行结果

在这里插入图片描述

Spring的AOP就是将公共业务代码(日志,事务,安全…),和业务类(真实对象)结合起来,实现公共业务的重复利用,解耦,它的本质是动态代理。

3.拓展:使用注解实现AOP

这里需要使用注解中的 @before @after
首先上面的业务实体类不变
然后编写注解的切入类:

package com.muzili.anno;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


//必须要写切面注解,否则就无法切入;
@Aspect
public class Anno {


    //切入点可以直接写到增强上面
    @Before("execution(* com.muzili.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=====================方法执行前=====================");
    }

    @After("execution(* com.muzili.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=====================方法执行后=====================");
    }

    //环绕增加
    //切入点参数 : ProceedingJoinPoint
    //环绕增强本质:
    /*
    将目标对象作为参数传递进方法中,
    在方法执行的前后,增加一些操作,仅此而已
    但是可以拿到一些目标对象的东西;
     */

    @Around("execution(* com.muzili.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("执行的切入点:"+jp.getSignature());//获得执行的切入点

        //执行目标方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");
        System.out.println(proceed); //null

    }
}


AOP是横向切面编程,它有五大通知类型,这里用到了环绕通知
在这里插入图片描述

又到了写核心配置文件的时候了
重复代码不再展示

<bean id="anno" class="com.muzili.anno.Anno"/>
<!--识别注解,自动代理-->
<aop:aspectj-autoproxy/>

编写测试类

@Test
public void test3(){
    ApplicationContext context = new ClassPathXmlApplicationContext("anno.xml");
    UserService userService = (UserService) context.getBean("userService");
    userService.add();
}

测试一下
在这里插入图片描述

到这儿就结束了,我相信看了本篇文章(关键是动手敲代码)再加上一些对AOP文字的描述,你对AOP横向编程会有不同的理解!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值