AOP
来源:互联网 发布:linux c setlocale 编辑:程序博客网 时间:2024/06/13 13:02
1.项目中如何在不修改核心业务的前提下植入新功能
例如:
1)事务处理
2)日志处理
3)缓存处理
4)权限处理
5)……………..
在项目中我们通常将核心业务(核心关注点)作为第一步实现,
扩展业务(横切关注点)作为第二步实现.
扩展实现如何植入
1)硬编码:修改核心业务添加扩展业务
2)抽取扩展业务,通过代理植入扩展业务
3)借助Spring AOP(底层依托于AspectJ框架)
2.代理模式分析及应用
1)静态代理(自己写代理类)
2)动态代理(依托于JDK API&反射机制)
3)CGLIB代理(被代理对象可以不实现接口)
3.Spring AOP
1) AOP 概述
a)Spring 中的一个核心组件(整合Aspectj框架实现)
b)面向切面编程,此切面通常称之为横切面
c)可以在对象运行时动态植入横切面功能.
2) AOP 相关术语
a)Aspect:切面(封装了扩展业务的一个对象类)
b)Pointcut:切入点(在哪个点上添加扩展业务:一般可以理解为方法集合)
c)JoinPoint: 连接点(一般指切入点中的一个方法)
d)Advice 通知(定义扩展业务中的相关步骤)
d.1)@Before
d.2)@After
d.3)@AfterThrowing
d.4)@AfterReturn
3)AOP 在spring中的实现
a) 创建一个Java maven项目
b) 添加AOP依赖(pom.xml)
c) 添加spring配置文件(例如:spring-aop.xml)
d) 创建业务接口及实现类(例如UserService)
e) 创建切面类对象(扩展业务类对象)
d) 创建单元测试类,为核心业务添加扩展业务
实例
/**用户业务接口*/public interface UserService { void saveUser(); void updateUser();}
package beans.service;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements UserService { public void saveUser() { System.out.println("save User"); throw new RuntimeException("save error"); } public void updateUser() { System.out.println("update User"); }}
/**通过@Aspect注解声明此类为一个切面类型 * 此类中要封装扩展业务 Advice (通知):通过Advice定义扩展业务中步骤 1)Before(前置通知) 2)After(最终通知) bean() 元素定义切入点 * */@Aspect@Componentpublic class TimeAspect { /**切入点*/ @Pointcut("bean(userServiceImpl)") public void pointCut(){} //@Before("bean(userServiceImpl)") @Before("pointCut()") public void begin(JoinPoint joinPoint){ //通过连接点获取方法签名,然后获取调用的方法名 String name=joinPoint.getSignature().getName(); System.out.println( name+".method.begin="+System.nanoTime()); } @AfterReturning("pointCut()") public void returnMethod(){ System.out.println( "method.return="+System.nanoTime()); } @AfterThrowing("pointCut()") public void throwMethod(){ System.out.println( "method.exception="+System.nanoTime()); } @After("bean(userServiceImpl)") public void end(){ System.out.println( "method.end="+System.nanoTime()); }}/** * try{ * @Before * @AfterReturn * }catch(){ * @AfterThrowing * }finally{ * @after * } */
import beans.service.UserService;public class TestService { ClassPathXmlApplicationContext ctx; @Before public void init(){ ctx=new ClassPathXmlApplicationContext( "spring-aop.xml") ; } @Test public void testSaveUser(){ UserService userService= ctx.getBean("userServiceImpl", UserService.class); userService.saveUser(); } @Test public void testUpdateUser(){ UserService userService= ctx.getBean("userServiceImpl", UserService.class); userService.updateUser(); } public void destory(){ ctx.close(); }}