spring通过配置+注解方式实现AOP环绕通知(全自动,即获取执行对象,直接获取被代理对象)(1、aop无法获取对象,类型转化异常错误记录。2、spring注解形式实现aop不要使用四大通知的解释)

spring通过注解的方式实现四大通知,只能用前置和后置,如果使用最终通知,该最终通知会在后置或者异常通知之前执行,spring现存问题,所以只演示spring通过注解方式全自动实现环绕通知。

1、引入依赖:

<!-- Spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.8.RELEASE</version>
</dependency>
<!--spring aop + aspectj-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.0.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.4</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

2、配置文件

<?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.ljs"/>
    <!--配置为自动代理-->
    <aop:aspectj-autoproxy/>
</beans>

3、接口

4、接口实现类,注意加组件注解,交给ioc管理。

 

5、切面类(需要指定为切面类:@Aspect。同时交由ioc管理:@Component)

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Around(value = "execution(* com.ljs.demo.*.*(..))")
    public Object around(ProceedingJoinPoint p) throws Throwable {

        System.out.println("执行方法前");

        for (Object arg : p.getArgs()) {
            System.out.println("参数:" + arg);
        }

        Object proceed = p.proceed(); //推进执行方法

        System.out.println("方法返回数据-> "+proceed.toString());

        System.out.println("执行方法后");

        return proceed;
    }

}

6、测试结果,这里一定注意,获取被代理对象,一定要用接口获取,否则会报错。

先记录错误写法:

报错信息:(类型转换异常)

java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to com.ljs.demo.DannyEat

正确写法:

7、控制台输出结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值