spring aop代理混用

本文探讨了Spring AOP中目标对象(织入对象)的类型问题,当目标对象为某接口的实现类时,Spring AOP的配置及运行机制。通过具体的代码示例和测试场景,展示了如何正确配置AOP切面来增强目标对象的方法。

就是目标对象(织入对象)不能是某接口的实现类

public interface User {
    void say();
}

public class UserImpl  implements User {

    public void say() {
        System.out.println("tom");
    }
}

织入类

public class MyAdivce {
    public void  before(){
        System.out.println("我叫");
    }
}

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       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-4.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

    <bean name="user" class="UserImpl"></bean>
    <bean name="myadivce" class="MyAdivce"></bean>
    <aop:config>
        <aop:pointcut id="pc" expression="execution(* UserImpl.*(..))"></aop:pointcut>
        <aop:aspect ref="myadivce">
            <aop:before method="before" pointcut-ref="pc"></aop:before>
        </aop:aspect>
    </aop:config>
    <!--<aop:aspectj-autoproxy  proxy-target-class="true"/>-->

</beans>

测试

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TT {
    @Test
    public void  test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-aop.xml");
        UserImpl user=context.getBean("user",UserImpl.class);
        user.say();
    }
}

会报

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'user' is expected to be of type 'UserImpl' but was actually of type 'com.sun.proxy.$Proxy7'

如果把测试类改成

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TT {
    @Test
    public void  test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-aop.xml");
        User user=context.getBean("user",Use.class);
        user.say();
    }
}

那user对象用的jdk
在这里插入图片描述
如果把UserImpl 的implements 去掉
那user对象用的是CGLib
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值