springAOP学习

springAOP


一、如何创建代理对象:

方法1:基于接口的动态代理。代码如下:

使用Proxy类中的newProxyInstance方法。

创建代理对象的要求:
      被代理对象(例如:生产厂家)最少实现一个接口,如果没有则不能使用。

newProxyInstance方法的参数:
      ClassLoader:类加载器。
            它是用于加载dial对象的字节码。(固定写法:被代理对象.getClass().getClassLoader())。
      Class[]:字节码数组。
            它是用于让代理对象和被代理对象有相同方法。(固定写法:被代理对象.getClass().getInterfaces())。
      InvocationHandler:用于提供增强代码。
            它是让我们写如何代理,一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。(注:此接口的实现类都是谁用谁写)。

public class Client {

    @Test
    public void proxyTest(){
        
        final Producer producer = new Producer();

        IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //在这填写增强的代码
                Object returnValue = null;
                //1.获取方法的执行的参数
                Float money = (Float) args[0];
                //2.判断当前方法是否是销售方法
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer, money * 0.8f);
                }
                return returnValue;
            }
        });
        proxyProducer.saleProduct(10000f);
    }
}

方法2:基于子类的动态对象。

要求:需要引入cglib的jar包

<!--注意这不会自动生成-->
		<dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1_3</version>
        </dependency>

在这里插入图片描述


creat方法的参数:
      Class:字节码。
            它是用于指定被代理对象的字节码。(固定写法:被代理对象.getClass())。
      Callback:用于提供增强代码。
            它是让我们写如何代理,一般都是些一个该接口的实现类,通常情况下都是匿名内部类,但不是必须的。(注:此接口的实现类都是谁用谁写)。我们一般写的都是改接口的子接口实现类:MethodInterceptor

代码如下:

/**
     * 基于子类的代理测试方法
     */
    @Test
    public void proxyTest1(){
        final Producer producer = new Producer();

        Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                //在这填写增强的代码
                Object returnValue = null;
                //1.获取方法的执行的参数
                Float money = (Float) objects[0];
                //2.判断当前方法是否是销售方法
                if("saleProduct".equals(method.getName())){
                    returnValue = method.invoke(producer, money * 0.8f);
                }
                return returnValue;
            }
        });
        cglibProducer.saleProduct(12000f);
    }

作用:可以利用代理模式来处理事务问题。

二、AOP的作用及优势

1.作用

在程序运行期间,不修改源码对已有方法进行增强。

2.优势

减少重复代码、提高开发效率、维护方便。

3.AOP实现方式

使用动态代理技术。

4.spring基于xml的AOP——编写必要的代码

编写pom.xml

<packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--切入点表达式依赖-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>

配置bean.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">

    <!--配置spring的ioc—把service对象配置进来-->
    <bean id="accountService" class="com.fjut.service.impl.AccountServiceImpl"></bean>

    <!--spring中基于XML的AOP配置
        1.把通知Bean也交给spring来管理
        2.使用AOP:config标签表名开始AOP的配置
        3.使用aop:aspect标签表面配置切面
        4.在aop:aspect标签的内部使用对应的标签来配置通知的类型
        5.pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强

            切入点表达式的写法
                关键字:execution(表达式)
                表达式:
                    标准写法:
                        访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
                    全通配写法:
                        * *..*.*(..)
                    实际开发中切入点表达式的通常写法:
                        切到业务层实现类下的所有方法:
                            * com.fjut.service.impl.*.*(..)
    -->

    <!--配置Logger类-->
    <bean id="logger" class="com.fjut.utils.Logger"></bean>

    <!--配置AOP-->
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--&lt;!&ndash;配置通知的类型,并且建立通知方法和切入点方法的关联&ndash;&gt;-->
            <!--<aop:before method="printLog" pointcut="execution(* com.fjut.service.impl.*.*(..))"></aop:before>-->

            <!--配置前置通知-->
            <aop:before method="beforePrintLog" pointcut="execution(* com.fjut.service.impl.*.*(..))"></aop:before>

            <!--配置后置通知-->
            <aop:after-returning method="afterPrintLog" pointcut="execution(* com.fjut.service.impl.*.*(..))"></aop:after-returning>

            <!--配置异常通知-->
            <aop:after-throwing method="exceptionPrintLog" pointcut="execution(* com.fjut.service.impl.*.*(..))"></aop:after-throwing>

            <!--配置最终通知-->
            <aop:after method="finalPrintLog" pointcut="execution(* com.fjut.service.impl.*.*(..))"></aop:after>
        </aop:aspect>
    </aop:config>
</beans>

4.spring基于注解的AOP——环绕通知方式

编写pom.xml

<packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--切入点表达式依赖-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>

配置bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.fjut"></context:component-scan>

    <!--配置spring开启注解AOP的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

对service进行注解配置,代码如下:

package com.fjut.service.impl;

import com.fjut.service.IAccountService;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements IAccountService{
    public void saveAccount() {
        System.out.println("执行了保存,执行了无返回值、无参的方法");
    }

    public void updateAccount(int i) {
        System.out.println("执行了更新,执行了无返回值、有参的方法");
    }

    public int deleteAccount() {
        System.out.println("执行了删除,执行了有返回值、无参的方法");
        return 0;
    }
}

对logger进行注解配置,代码如下:

package com.fjut.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**
 * 用于记录日志的工具类,它里面提供了公共的代码
 */
@Component("logger")
@Aspect //表示当前类是一个切面类
public class Logger {

    @Pointcut("execution(* com.fjut.service.impl.*.*(..))")
    public void pt(){}
    
    @Around("pt()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        Object returnValue = null;
        try{
            Object[] args = pjp.getArgs();  //得到方法执行说需要的参数

            System.out.println("前置通知日志记录");

            returnValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("后置通知日志记录");

            return returnValue;
        }catch (Throwable t){
            System.out.println("异常通知日志记录");
            throw new RuntimeException(t);
        }finally {
            System.out.println("最终通知日志记录");
        }
    }
}

测试。代码如下:

package com.fjut.test;

import com.fjut.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试aop配置
 */
public class AOPTest {

    @Test
    public void testAop(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //获取对象
        IAccountService as = (IAccountService) ac.getBean("accountService");
        //执行方法
        as.saveAccount();
    }
}

总结

可以利用代理模式来处理事务问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值