- # 基于代理类的 AOP 实现:
- step1:
- 1 package com.sjl.factorybean;
- 2 /** 切面类 */
- 3 import org.aopalliance.intercept.MethodInterceptor;
- 4 import org.aopalliance.intercept.MethodInvocation;
- 5
- 6 public class MyAspect implements MethodInterceptor {
- 7 @Override
- 8 public Object invoke(MethodInvocation mi) throws Throwable {
- 9 check_Permission();
- // 用 proceed 方法来执行当前对象
- 10 Object obj=mi.proceed();
- 11 log();
- 12 return obj;
- 13 }
- // 目标方法执行前执行 check_Permission 方法
- 14 public void check_Permission(){
- 15 System.out.println("模拟检查权限日志");
- 16 }
- // 目标方法执行后执行 log() 方法
- 17 public void log(){
- 18 System.out.println("模拟记录日志");
- 19 }
- 20 }
- # 目标类:
- package com.sjl.jdk;
- /**
- * UserDaoImpl 是目标类, 对其中的方法进行增强处理;
- */
- public class UserDaoImpl implements UserDao{
- @Override
- public void addUser() {
- System.out.println("添加用户");
- }
- @Override
- public void deleteUser() {
- System.out.println("删除用户");
- }
- }
- #step2: 创建配置文件, 并指定代理对象:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
- <!-- 1 目标类 id 为 "userDao" class="目标类的全限定名" -->
- <bean id="userDao" class="com.sjl.jdk.UserDaoImpl"></bean>
- <!-- 2 切面类 id 为 "myAspect" class="切面类的全限定名"-->
- <bean id="myAspect" class="com.sjl.factorybean.MyAspect"></bean>
- <!-- 3 使用 Spring 代理工厂定义一个名称为 userDaoProxy 的代理对象, 而 aop
- 实现的就是代理工厂 bean id 全限定名为如上图 -->
- <bean id="userDaoProxy"
- class="org.springframework.aop.framework.ProxyFactoryBean">
- <!-- 3.1 指定代理实现的接口 proxyInterfaces value 为 com.sjl.jdk.UserDao-->
- <property name="proxyInterfaces" value="com.sjl.jdk.UserDao" />
- <!-- 3.2 指定目标对象名为 target 目标类的对象属性 ref 为目标类的 id-->
- <property name="target" ref="userDao" />
- <!-- 3.3 指定切面名 interceptorNames, 织入环绕通知 myAspect -->
- <property name="interceptorNames" value="myAspect" />
- <!-- 3.4 指定代理方式, true: 使用 cglib,false(默认): 使用 jdk 动态代理 -->
- <property name="proxyTargetClass" value="true" />
- </bean>
- </beans>
- <!-- 用配置文件指定代理对象, 包括目标类, 切面类, 并指定 Spring 代理工厂定义一个名称为
- userDaoProxy 的代理对象, 其中包含接口的 id 代理工厂的类, 从 aop 的包中找, 指定接口, 再
- 指定属性, 接口, 目标对象, 切面和代理方式等 -->
- #step3: 测试类
- package com.sjl.factorybean;
- import org.springframework.context.ApplicationContext;
- import
- org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.sjl.jdk.UserDao;
- // 测试类
- public class ProxyFactoryBeanTest {
- public static void main(String args[]) {
- String xmlPath = "applicationContext.xml";
- ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
- // 从 Spring 容器获得内容
- UserDao userDao = (UserDao) applicationContext.getBean("userDaoProxy");
- // 执行方法
- userDao.addUser();
- userDao.deleteUser();
- }
- }
来源: http://www.bubuko.com/infodetail-2946251.html