Spring5—AOP

导读:本篇文章讲解 Spring5—AOP,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1.AOP

1.1什么是AOP

AOP为Aspect Oriented Programming的缩写,意为: 面向切面编程 ,通过 预编译 方式和运行期间动态代理实现程序功能的统一维护的一种技术。 AOP是 OOP 的延续,是软件开发中的一个热点,也是 Spring 框架中的一个重要内容,是 函数式编程 的一种衍生范型。 利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的 耦合度 降低,提高程序的可重用性,同时提高了开发的效率。

1.2AOP在Spring中的作用

提供声明式事务,允许用户自定义切面

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志等等…
  • 切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。如日志类
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。如日志类中的方法
  • 目标(Target):被通知对象。类似一个接口
  • 代理(Proxy):向目标对象应用通知之后创建的对象。(代理对象)
  • 切入点(PointCut):切面通知执行的“地点“的定义连接点。
  • 连接点(JointPoint):与切入点匹配的执行点。

1.3使用Spring实现AOP

  • 搭建环境:

    • 接口类:
public interface UserService {

    public void add();
    public void delete();
    public void update();
    public void select();
}

​ 接口实现类:

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 select() {
        System.out.println("查询一个用户");
    }
}
  • 使用AOP织入,需要导入一个依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
    <scope>runtime</scope>
</dependency>
  • 还需要在配置文件顶部配置aop约束
    • xmlns:aop=“http://www.springframework.org/schema/aop”
    • http://www.springframework.org/schema/aop
    • https://www.springframework.org/schema/aop/spring-aop.xsd
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    
</beans>

方式一:使用Spring的API接口【SpringAPI接口实现】

1.编写相关类

  • 前置日志类:
public class Log implements MethodBeforeAdvice {

    //method:要执行的目标对象的方法
    //objects:参数
    //o:目标对象
    @Override
    public void before(Method method, Object[] args, Object taret) throws Throwable {
        System.out.println(taret.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
  • 后置日志类:
public class AfterLog implements AfterReturningAdvice {
    //returnvalue:返回值
    @Override
    public void afterReturning(Object returnvalue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了" + method.getName()+"返回结果为"+ returnvalue);
    }
}

2.编写配置文件

​ 在配置文件中进行配置

<!--    注册bean-->
    <bean id="UserService" class="service.UserServiceImpl"/>
<!--    给前置日志和后置日志注册bean-->
    <bean id="log" class="Log.Log"/>
    <bean id="afterlog" class="Log.AfterLog"/>

<!--    方式一:使用原生Spring API接口-->
<!--    配置AOP:需要导入aop的约束-->
    <aop:config>
<!--        切入点:expression:表达式,execution(要执行的位置,里面最后的.*(..)代表该类的全部方法以及参数)-->
        <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))"/>

<!--            执行环绕增加,pointcut-ref:切入点的引用-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="afterlog" pointcut-ref="pointcut"/>

    </aop:config>

[execution表达式用法]((39条消息) 白话Spring(基础篇)—AOP(execution表达式)_y-yg的博客-CSDN博客_aop execution 表达式)

符号 含义
execution() 表达式的主体;
第一个”*“符号 表示返回值的类型任意
com.sample.service.impl AOP所切的服务的包名,即,我们的业务部分
包名后面的”…“ 表示当前包及子包
第二个”*“ 表示类名,*即所有类。此处可以自定义
.*(…) 表示任何方法名,括号表示参数,两个点表示任何参数类型

3.测试

public class mytest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口,所以返回的类型必须得写接口
        UserService userservice = (UserService) context.getBean("UserService");

        userservice.add();
    }
}

方式二:自定义类实现AOP【主要是切面定义】

1.自定义切面类

public class DiyPointCut {

    public void before(){
        System.out.println("方法执行前");
    }

    public void after(){
        System.out.println("方法执行后");
    }

}

2.在配置文件中配置aop

<!--    方式二:自定义类-->
    <bean id="diy" class="diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面,ref:要引用的类的beanid-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
<!--            通知,method:切面里面的方法-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

3.测试

public class mytest {
	public static void main(String[] args) {
    	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    	//动态代理的是接口,所以返回的类型必须得写接口
    	UserService userservice = (UserService) context.getBean("UserService");

    	userservice.add();
	}
}

方式三:使用注解实现AOP

1.编写注解类

@Aspect//标志这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("方法执行前");
    }

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

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable{
        System.out.println("环绕前");

        //获得签名,签名就是所执行的方法名
        Signature signature = jp.getSignature();
        System.out.println("签名为" + signature);
        //执行方法
        Object proceed = jp.proceed();

        System.out.println("环绕后");
    }
}

2.在beans里面配置该类

<!--    方式三-->
	<bean id="UserService" class="service.UserServiceImpl"/>
    <bean id="annotationPointCut" class="diy.AnnotationPointCut"/>
<!--    开启注解支持      JDK(默认proxy-target-class=false) 另外一种是cglib-->
    <aop:aspectj-autoproxy proxy-target-class="false"/>

3.测试:

public class mytest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口,所以返回的类型必须得写接口
        UserService userservice = (UserService) context.getBean("UserService");

        userservice.add();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84168.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!