[Spring]9.AOP


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

aop的术语

参考:
https://blog.csdn.net/Bronze5/article/details/106746705/

image

Spring实现AOP:

1.导入依赖
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
            <scope>runtime</scope>
        </dependency>
2.写业务类

image

3.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
	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>
4.写增加的功能
public class AfterLog implements AfterReturningAdvice {

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"实现了"+method.getName()+"方法,返回值为:"+returnValue);
    }
}
public class BeforeLog implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"类的"+method.getName()+"方法被执行了");
    }
}
5.在xml中配置

先装配bean

    <bean id="userService" class="com.wang.service.UserServiceImppl"/>
    <bean id="beforeLog" class="com.wang.log.BeforeLog"/>
    <bean id="afterLog" class="com.wang.log.AfterLog"/>

再配置aop

    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserServiceImppl.*(..))"/>
        <aop:advisor pointcut-ref="pointcut" advice-ref="beforeLog"/>
        <aop:advisor pointcut-ref="pointcut" advice-ref="afterLog"/>
    </aop:config>

其中execution的语法为:execution(修饰符 返回值 包名.类名/接口名.方法名(参数列表))。
返回类型、方法名、参数是必须有的.

6.测试

image

image

使用Aspect实现aop

  1. 建立自定义aspect
    image
  2. 去xml中注册aspect的bean
    <bean id="aspect" class="com.wang.aspect.Aspect"/>
  3. 在xml中注册切面
    <aop:config>
        <aop:aspect ref="aspect">
            <aop:pointcut id="pointcut" expression="execution(* com.wang.service.UserService.*(..))"/>
            <aop:before method="BeforeLog" pointcut-ref="pointcut"/>
            <aop:after method="AfterLog" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>
  1. 测试结果
    image

使用注解实现aop

  1. 在xml中加上
<aop:aspectj-autoproxyautoproxy\>

开启注解
2. 编写切面类
image
3. 在xml中注册bean

<bean id="annoAspect" class="com.wang.aspect.AnnotationAspect"/>

4.测试
image

posted @ 2021-11-25 16:49  从零开始学java_wxz  阅读(38)  评论(0)    收藏  举报