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>