【Spring框架08】AOP初步学习

【Spring框架08】AOP初步学习

思维导图

在这里插入图片描述

一、代理模式

1.jdk实现动态代理

(1)代理的函数

public class MyTest {
    public void Test(){
        System.out.println("我自己的步骤");
    }
}

(2)基于接口思想实现动态代理

public class JdkHandler implements InvocationHandler {

//    目标对象
    private Object target;

    public JdkHandler(Object target){
        this.target=target;
    }

//    程序运行期创建代理对象,动态创建代理对象
    public Object getProxy(){
        return Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    public void before(){
        System.out.println("步骤一");
    }
    public void after(){
        System.out.println("步骤三");
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(target,args);
        after();
        return result;
    }
}

(3)调用测试

public class JdkHandlerTest extends TestCase {

    public void testInvoke() throws Throwable {
        MyTest myTest = new MyTest();
        JdkHandler jdkHandler = new JdkHandler(myTest);
//        创建代理对象
        Object proxy=jdkHandler.getProxy();

        jdkHandler.invoke(proxy,MyTest.class.getMethod("Test"),null);
    }
}

2.cglib动态代理

(1)需要引入cglib依赖

  <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2.2</version>
    </dependency>

(2)基于继承思想实现

public class CglibHandlerTest implements MethodInterceptor {

//    目标对象
    private Object target;

    public CglibHandlerTest(Object target) {
        this.target = target;
    }

//    运行期间动态创建代理类
    public Object getProxy(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public void before(){
        System.out.println("步骤一");
    }
    public void after(){
        System.out.println("步骤三");
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invoke(target,args);
        after();
        return result;
    }
}

(3)编写测试类用于代理继承

public class CglibHandlerTestTest extends TestCase {

    public void testIntercept() {
        MyTest myTest = new MyTest();
        CglibHandlerTest cglibHandlerTest = new CglibHandlerTest(myTest);
        MyTest myTest11 = (MyTest)cglibHandlerTest.getProxy();
        myTest11.Test();
    }
}

配置aop的maven依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.lcy</groupId>
  <artifactId>spring08-AOP</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>spring08-AOP</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

<!--    Aop依赖 只支持xml(spring自带)-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
<!--    支持注解(第三方)-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.6.11</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.11</version>
    </dependency>

  </dependencies>

  <build>
  </build>
</project>

二、解决日志处理问题

1.基于注解的方式

配置aop的命名空间和网址并开启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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd

       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:component-scan base-package="com.lcy"/>
<!--    开启aop代理-->
    <aop:aspectj-autoproxy/>
</beans>

模拟类

@Service
public class UserService {
    public void add(){
        System.out.println("UserService add……》》》");
    }
}

切面

package com.lcy.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LogCut {

    //定义切入点(扫描该包下的所有类所有方法)
    @Pointcut("execution(* com.lcy.service..*.*(..))")
    public void cut(){}

    @Before("cut()")
    public void before(){
        System.out.println("前置通知");
    }

    @After("cut()")
    public void after(){
        System.out.println("后置通知");
    }

    @AfterReturning("cut()")
    public void afterReturn(){
        System.out.println("返回通知");
    }

    @AfterThrowing(value = "cut()",throwing = "e")
    public void afterThrow(Exception e){
        System.out.println("异常通知"+e.getMessage());
    }

    @Around("cut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕通知前");
        //内存信息。。。。访问方法
        System.out.println(pjp.getTarget()+"...."+pjp.getSignature());
        Object result =pjp.proceed();//继续向下执行
        System.out.println("环绕通知后");
        return result;
    }
}

正常运行没有报异常,有返回通知
在这里插入图片描述
不能正常运行,有异常通知,但是没有返回通知
在这里插入图片描述

2.基于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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd

       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
<context:component-scan base-package="com.lcy"/>
<!--    开启aop代理-->
    <aop:aspectj-autoproxy/>

<!--    配置AOP-->
    <bean id="logCut02" class="com.lcy.aop.LogCut02"></bean>
    <aop:config>
        <aop:aspect ref="logCut02">
        <aop:pointcut id="cut" expression="execution(* com.lcy.service..*.*(..))"/>
            <aop:before method="before" pointcut-ref="cut"></aop:before>
            <aop:after method="after" pointcut-ref="cut"></aop:after>
            <aop:after-returning method="afterReturn" pointcut-ref="cut"></aop:after-returning>
            <aop:after-throwing method="afterThrow" pointcut-ref="cut" throwing="e"></aop:after-throwing>
            <aop:around method="around" pointcut-ref="cut"></aop:around>
        </aop:aspect>
    </aop:config>
</beans>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值