Spring基于代理类的AOP实现

ProxyFactoryBean是FactoryBean接口的实现类,FactoryBean负责实例化一个Bean, 而ProxyFactoryBean负 贵为其他Bean创建代理实例。在Spring中,使用ProxyFactoryBean是创建AOP代理的基本方式。
案例:

  • 目标类:
//目标类
public class UserDaoImpl implements UserDao {
    @Override
    public void addUser() {
        System.out.println("添加用户");
    }

    @Override
    public void deleteUser() {
        System.out.println("删除用户");
    }
}
  • 切面类:
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

//切面类
public class MyAspect implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        check_Permissions();
        //执行目标方法
        Object obj = mi.proceed();
        log();
        return obj;
    }
    public void check_Permissions(){
        System.out.println("模拟检查权限...");
    }
    public void log(){
        System.out.println("模拟记录日志...");
    }
}
  • 配置文件:
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1 目标类 -->
    <bean id="userDao" class="com.no5.proxyaop.UserDaoImpl"/>
    <!-- 2 切面 -->
    <bean id="myAspect" class="com.no5.proxyaop.MyAspect"/>
    <!-- 3 使用Spring代理工厂定义一个名称为userDaoProxy的代理对象 -->
    <bean id="userDaoProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <!-- 3.1 指定代理实现的接口 -->
        <property name="proxyInterfaces" value="com.no5.proxyaop.UserDao"/>
        <!-- 3.2 指定目标对象 -->
        <property name="target" ref="userDao"></property>
        <!-- 3.3 指定切面,织入环绕通知-->
        <property name="interceptorNames" value="myAspect"/>
        <!-- 3.4 指定代理方式,true:使用cglib; false:使用jdk动态代理 -->
        <property name="proxyTargetClass" value="true"/>
    </bean>

</beans>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值