基于Spring和AOP的数据库认证日志的设计与实现
SpringBoot使用SpringAOP实现日志审计等功能

SpringBoot使⽤SpringAOP实现⽇志审计等功能项⽬当中需要对⽤户操作菜单的⾏为记录⽇志,⽤SpringAOP写了个⼤概实现,切点是采⽤注解的⽅式,⽤包名的⽅式虽然也可以达到相同的效果,但是不如注解⽅式灵活⽅便。
不多说,直接上代码,此处只是简单写写实现原理。
⼯程⽬录:pom.xml引⼊以下依赖:<!-- 热部署模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional><!-- 这个需要为 true 热部署才有效 --></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- spring-boot aop依赖配置引⼊ --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>注解:@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface Action {String description() default "no description";}Controller类:/*** @auther: gaopeng*/@RestControllerpublic class AspectController {/*** ⾛切⾯* @return*/@GetMapping("/test")@Action(description = "执⾏了test操作菜单")public String test(){return "method return";}/*** 不⾛切⾯*/@GetMapping("/test1")private void test1(){}/*** ⾛切⾯,抛异常*/@GetMapping("/throws")@Action(description = "执⾏了throws菜单但是抛了异常")public void throwsException(){throw new RuntimeException();}}切⾯类:/*** @auther: gaopeng*/@Aspect@Componentpublic class TestAspect {/*** 切⼊点*/// 此处的切点是注解的⽅式,也可以⽤包名的⽅式达到相同的效果//@Pointcut("execution(public * com.gaopeng.springboot.mytest.controller.*.*(..))")@Pointcut("@annotation(com.gaopeng.springboot.mytest.annotation.Action)")public void execute(){}/*** 前置通知* @param joinPoint*/@Before(value ="execute()")public void Before(JoinPoint joinPoint) {System.out.println("执⾏⽅法之前");}/*** 环绕通知* @param proceedingJoinPoint* @return*/@Around(value ="execute()")public Object around(ProceedingJoinPoint proceedingJoinPoint) {System.out.println("环绕通知开始");try {System.out.println("执⾏⽅法:" + proceedingJoinPoint.getSignature().getName()); MethodSignature signature =(MethodSignature) proceedingJoinPoint.getSignature(); Action action = signature.getMethod().getAnnotation(Action.class);System.out.println("菜单="+action.description());Object object = proceedingJoinPoint.proceed();System.out.println("环绕通知结束,⽅法返回:" + object);return object;} catch (Throwable e) {System.out.println("执⾏⽅法异常:" + e.getClass().getName());return null;}}/*** 后置通知* @param joinPoint*/@After(value ="execute()")public void After(JoinPoint joinPoint) {System.out.println("执⾏⽅法之后");}/*** 后置通知,带返回值* @param obj*/@AfterReturning(pointcut = "execute()",returning = "obj")public void AfterReturning(Object obj) {System.out.println("执⾏⽅法之后获取返回值:"+obj);}/*** 后置通知,异常时执⾏* @param e*/@AfterThrowing(throwing = "e",pointcut = "execute()")public void doAfterThrowing(Exception e) {System.out.println("执⾏⽅法异常:"+e.getClass().getName());}}运⾏结果:。
Spring Boot框架中的应用监控与日志管理

Spring Boot框架中的应用监控与日志管理Spring Boot框架是一款基于Spring框架的微服务构建工具,它简化了Spring应用程序的开发过程,并集成了许多常用的功能模块。
其中,应用监控与日志管理是Spring Boot框架中非常重要的功能之一,它能够帮助开发人员实时监控应用的运行状态,及时发现和解决问题,并记录应用的运行日志以便后续分析和排查问题。
本文将深入探讨Spring Boot框架中应用监控与日志管理的相关内容,包括具体功能、实现原理以及最佳实践。
应用监控是保证应用高可用性和高性能的关键手段之一。
Spring Boot框架提供了丰富的监控功能,包括健康检查、性能指标、HTTP追踪等。
其中,健康检查是最为基础和重要的监控功能,通过访问/actuator/health端点,可以获取当前应用的健康状态。
Spring Boot框架默认集成了很多自动配置的健康检查项,包括数据库连接、磁盘空间、线程池状态等。
除此之外,开发人员还可以扩展自定义的健康检查项,比如检查外部服务的可用性。
性能指标是另一个重要的监控功能,Spring Boot框架通过Micrometer库提供了丰富的性能指标支持,包括内存使用、CPU负载、请求处理时间等。
借助这些性能指标,开发人员可以实时监控应用的性能表现,并做出相应的调优优化。
日志管理是应用监控的重要组成部分,它记录了应用运行过程中产生的各种信息,包括调试信息、错误信息、警告信息等。
Spring Boot框架提供了强大的日志管理功能,基于Logback库实现了灵活的日志配置和强大的日志输出。
开发人员可以通过application.properties或application.yml文件,配置日志级别、日志输出目标、日志格式等参数,满足不同环境下的日志记录需求。
同时,Spring Boot框架还提供了统一的日志输出接口,开发人员可以通过Log接口进行日志输出,而无需关心具体的日志实现。
SpringAOP的原理和应用场景

SpringAOP的原理和应用场景SpringAOP(Aspect-Oriented Programming)是Spring框架中的一个重要组成部分,它提供了一种通过预定义的方式,将横切关注点(Cross-cutting Concerns)与业务逻辑进行解耦的机制。
本文将介绍SpringAOP的原理及其在实际应用场景中的应用。
一、SpringAOP的原理SpringAOP基于代理模式(Proxy Pattern)实现。
在SpringAOP中,通过生成与原始类(被代理类)具有相同接口的代理类,将横切逻辑编织到业务逻辑中。
在运行时,当调用代理类的方法时,会在方法执行前、后或异常抛出时插入相应的横切逻辑代码。
具体而言,SpringAOP使用了以下几个核心概念:1. 切面(Aspect):切面是横切逻辑的模块化单元,它包含了一组通知(Advice)和切点(Pointcut)。
2. 通知(Advice):通知定义了实际的横切逻辑代码,并规定了何时执行该代码。
SpringAOP提供了五种类型的通知:前置通知(Before)、后置通知(After)、返回通知(After-returning)、异常通知(After-throwing)和环绕通知(Around)。
3. 切点(Pointcut):切点指定了在哪些连接点(Join Point)上执行通知。
连接点可以是方法调用、属性访问等程序执行的点。
4. 连接点(Join Point):连接点是程序执行过程中的一个特定点,如方法调用前、方法调用后等。
通知通过切点来选择连接点。
5. 织入(Weaving):织入是将切面应用到目标对象,并创建代理对象的过程。
织入可以在编译时、类加载时或运行时进行。
二、SpringAOP的应用场景SpringAOP可应用于各种场景,用于解决跨越多个模块或类的横切关注点问题。
以下是一些常见的SpringAOP应用场景:1. 日志记录:通过在关键方法的前后插入日志代码,实现对系统运行状态的监控和记录。
SpringAOP示例与实现原理总结——传统springaop、基于切面注入、基于@Asp。。。

SpringAOP⽰例与实现原理总结——传统springaop、基于切⾯注⼊、基于@Asp。
⼀、代码实践1)经典的Spring Aop经典的spring aop,是基于动态代理技术的。
实现⽅式上,最常⽤的是实现MethodInterceptor接⼝来提供环绕通知,创建若⼲代理,然后使⽤ProxyBeanFactory配置⼯⼚bean,⽣成拦截器链,完成拦截。
⽰例如下:1package demo.spring;23import org.aopalliance.intercept.MethodInterceptor;4import org.aopalliance.intercept.MethodInvocation;5import org.junit.Test;6import org.junit.runner.RunWith;7import org.springframework.beans.factory.annotation.Autowired;8import org.springframework.test.context.ContextConfiguration;9import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;1011 @RunWith(SpringJUnit4ClassRunner.class)12 @ContextConfiguration("classpath:spring-config.xml")13public class TraditionalSpringAopDemo {14 @Autowired15private Service proxy;1617 @Test18public void test() {19 proxy.execute("hello world!");20 }21 }2223interface Service {24void execute(String str);25 }2627class ServiceImpl implements Service {28 @Override29public void execute(String str) {30 System.out.println("execute invoke: " + str);31 }32 }3334class Interceptor1 implements MethodInterceptor {35 @Override36public Object invoke(MethodInvocation methodInvocation) throws Throwable {37 System.out.println("interceptor1,before invoke");38 Object ret = methodInvocation.proceed();39 System.out.println("interceptor1,after invoke");40return ret;41 }42 }4344class Interceptor2 implements MethodInterceptor {45 @Override46public Object invoke(MethodInvocation methodInvocation) throws Throwable {47 System.out.println("interceptor2,before invoke");48 Object ret = methodInvocation.proceed();49 System.out.println("interceptor2,after invoke");50return ret;51 }52 }xml⽂件配置:1<?xml version="1.0" encoding="UTF-8"?>2<beans xmlns="/schema/beans"3 xmlns:xsi="/2001/XMLSchema-instance"4 xmlns:context="/schema/context"5 xmlns:aop="/schema/aop"6 xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd /schema/context /schema/context/sprin 78<context:component-scan base-package="demo.spring"/>910<bean class="demo.spring.ServiceImpl" id="service"></bean>11<bean class="demo.spring.Interceptor1" id="interceptor1"></bean>12<bean class="demo.spring.Interceptor2" id="interceptor2"></bean>13<bean class="org.springframework.aop.framework.ProxyFactoryBean" id="proxy">14<property name="target" ref="service"/>15<property name="interceptorNames">16<list>17<value>interceptor1</value>18<value>interceptor2</value>19</list>20</property>21</bean>22</beans>结果:interceptor1,before invokeinterceptor2,before invokeexecute invoke: hello world!interceptor2,after invokeinterceptor1,after invoke可以看到拦截链的执⾏过程与拦截器顺序的关系。
基于Annotation的Spring AOP日志处理的设计与实现

Value Engineering0引言AOP (Aspect Oriented Programming ,向切面编程)是建立在OOP (Object Oriented Programming ,面向对象程序设计)基础之上的,OOP 针对问题领域中以及业务处理过程中存在的实体及其属性和操作进行抽象和封装,面向对象的核心概念是纵向结构的,其目的是获得更加清晰高效的逻辑单元划分;而AOP 则是针对业务处理过程中的切面进行提取,例如,某一个操作(例如日志输出)在各个模块中都有涉及,这个操作就可以看成“横切”存在于系统当中。
在许多情况下,这些操作都是与业务逻辑相关性不强或者不属于逻辑操作的必须部分,而面向对象的方法很难对这种情况做出处理。
AOP 则将这些操作与业务逻辑分离,使程序员在编写程序时可以专注于业务逻辑的处理,而利用AOP 将贯穿于各个模块间的横切关注点自动耦合进来[1]。
AOP 被定义为一种编程技术,用来在系统中提升业务的分离,它将服务模块化,使得业务层完全没必要理会这些服务的存在,比如日志,事务,安全等。
1Spring AOP 的Annotation 方式的技术要点1.1Annotation 技术sun 公司从J2SE 5.0开始提供名为Annotation (注释)的功能,它被定义为JSR-175规范[2],是Java 语言中的一种特殊的元数据语法,可以被添加到Java 代码中。
类,方法,变量,参数,包都可以被标注。
Annotation 是可以被反射的,因为它们被编译器生成嵌入在编译后文件,并保留在虚拟机中以便在运行时被索引[3]。
注释是以“@注释名”在代码中存在,一般只有一行,也可以包含有任意的参数。
从Spring2.0以后的版本中,集成了AspectJ 注解。
AOP 的实现有多种方式,使用Annotation 方式的配置,无需配置文件,只需要通过添加“注释代码”来完成,简化了Spring 的开发,容易对方法进行拦截。
基于SpringBootAdminLTE3的博客管理系统设计与实现

1、用户管理:包括用户注册、 登录、信息修改等功能。
2、博客管理:包括文章创建、编辑、发布、删除等功能,同时支持文章分类。
3、评论管理:允许用户对博客文章进行评论,管理员可以删除或置顶评论。
4、标签管理:为博客文章添加标签,方便用户浏览相关文章。
5、统计功能:统计博客访问量、评论数等数据,以可视化图表展示。
在部署方面,我们采用了Docker容器化技术,将应用程序打包成Docker镜像, 并使用Docker Compose进行容器编排。通过这种方式,我们可以快速部署和 扩展系统,以满足不同规模的应用需求。
通过基于Spring Boot AdminLTE3的博客管理系统设计与实现,我们成功地构 建了一个功能完善、易于维护的博客平台。该平台具有高度的可扩展性和可定 制性,可以根据实际需求进行二次开发和扩展。该平台具有良好的用户体验和 数据可视化效果,使得用户和管理员能够更加方便地进行信息交互和管理操作。
展望未来,我们将继续对该系统进行优化和改进。计划包括加强安全性措施、 引入算法提升文章推荐准确性、支持多语言翻译等扩展功能。我们也希望能够 吸引更多的开发者加入到这个项目中来,共同完善和优化这个博客管理系统, 为互联网用户提供更好的服务。
谢谢观看
在实现中,我们使用了AdminLTE的布局、组件和插件,如Sidebar、Navbar、 Grid等。同时,通过自定义CSS样式和JavaScript脚本,实现了评论、标签等 功能的动态展示和交互效果。此外,我们还利用ECharts等可视化库实现了数 据统计图表的展示。
我们对系统进行了详细的测试,包括单元测试、集成测试和功能测试等。通过 测试,我们发现并解决了一些潜在的问题和缺陷,确保系统的稳定性和可靠性。
Hale Waihona Puke 本系统基于Spring Boot框架进行开发,充分利用了Spring Boot的自动化配 置和轻量级开发的优势。我们使用Spring Data JPA作为数据持久层,使得数 据库操作更加便捷。此外,系统还集成了AdminLTE3前端框架,以提供美观、 易用的用户界面。
spring的意思

spring的意思Spring的意思Spring是一种开源的、轻量级的、全栈的Java应用开发框架。
它是基于IoC(Inversion of Control)和AOP(Aspect-Oriented Programming)的编程模型,旨在简化企业级应用程序的开发。
首先,Spring的“意思”可以从字面上理解为春天的意思。
春天象征着新生、希望与活力。
同样,Spring框架为Java应用程序注入了新的活力与创造力,使得开发人员能够更加轻松地构建高效、可靠的应用程序。
Spring框架的核心特点是IoC和AOP:1. IoC(Inversion of Control):传统的编程模型中,应用程序的各个组件之间通常直接进行耦合。
而Spring采用IoC容器,将对象的依赖关系交由容器进行管理,通过配置文件或注解将对象之间的依赖关系进行解耦。
开发者只需关注业务逻辑的实现,而无需关心对象的创建和销毁,大大简化了开发流程。
2. AOP(Aspect-Oriented Programming):AOP是一种编程范式,与IoC相辅相成。
通过AOP,开发者可以将一些与业务逻辑无关但又需要在多个对象中复用的功能(如日志记录、性能监测等)进行横向抽取,并通过切面(Aspect)的方式进行集中管理。
Spring框架提供了强大的AOP支持,能够在不修改原有代码的情况下,动态地向程序中插入额外的功能。
Spring框架的设计理念是“面向接口编程”,它鼓励开发者通过接口定义业务逻辑,借助IoC容器将不同的实现进行组装。
这种松耦合的设计方式使得应用程序更加灵活、易于维护和扩展。
除了IoC和AOP,Spring框架还提供了许多其他功能和模块,方便开发者构建各种不同类型的应用程序:1. 数据访问层:Spring提供了对各种数据访问技术的支持,包括JDBC、ORM(如Hibernate)、NoSQL数据库等。
通过Spring的事务管理,开发者可以轻松地控制数据库事务,确保数据一致性。
SpringAOP切面日志Demo配置文件方式与注解方式

SpringAOP切⾯⽇志Demo配置⽂件⽅式与注解⽅式⼀、配置⽂件⽅式1、配置applicationContext.xml,<bean id="logAopBean"class="mon.aop.LogAop"></bean><aop:config><aop:aspect id="logAspect"ref="logAopBean"><aop:pointcut expression="execution(* com.demo..*(..))" id="allMethod"/><aop:before method="before" pointcut-ref="allMethod" /><aop:after-throwing method="afterThrowing" pointcut-ref="allMethod" /><aop:after-returning method="afterReturn" pointcut-ref="allMethod" /><aop:after method="after" pointcut-ref="allMethod" /></aop:aspect></aop:config>2、⽇志处理类,/*** LogAop.java** Shanghai NTT DATA Synergy Software Co., Ltd. All Rights Reserved.* @author wyl* @date 2016-10-18*/package mon.aop;import ng.JoinPoint;import ng.ProceedingJoinPoint;/*** @author wyl* @Description TODO* @date 2016-10-18**/public class LogAop {public void before(JoinPoint call){String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println("开始执⾏:"+className+"."+methodName+"()⽅法...");}public void afterThrowing(JoinPoint call){String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()⽅法抛出了异常...");}public void afterReturn(JoinPoint call){String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()⽅法正常执⾏结束...");}public void after(JoinPoint call){String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()最终执⾏步骤(finally)...");}/*//⽤来做环绕通知的⽅法可以第⼀个参数定义为ng.ProceedingJoinPoint类型public Object doAround(ProceedingJoinPoint call) throws Throwable {Object result = null;this.before(call);//相当于前置通知try {result = call.proceed();this.afterReturn(call); //相当于后置通知} catch (Throwable e) {this.afterThrowing(call); //相当于异常抛出后通知throw e;}finally{this.after(call); //相当于最终通知}return result;}*/}⼆、注解⽅式1、配置applicationContext.xml,<bean id="logAspectBean"class="mon.aop.LogAnnotationAspect"></bean> <aop:aspectj-autoproxy/>2、⽇志处理类,/*** LogAnnotationAspect.java** Shanghai NTT DATA Synergy Software Co., Ltd. All Rights Reserved.* @author wyl* @date 2016-10-18*/package mon.aop;import ng.JoinPoint;import ng.ProceedingJoinPoint;import ng.annotation.After;import ng.annotation.AfterReturning;import ng.annotation.AfterThrowing;import ng.annotation.Aspect;import ng.annotation.Before;import ng.annotation.Pointcut;/*** @author wyl* @Description TODO* @date 2016-10-18**/@Aspect //定义切⾯类public class LogAnnotationAspect {@SuppressWarnings("unused")//定义切⼊点,提供⼀个⽅法,这个⽅法的名字就是改切⼊点的id@Pointcut("execution(* com.demo..*(..))")private void allMethod(){}//针对指定的切⼊点表达式选择的切⼊点应⽤前置通知@Before("allMethod()")public void before(JoinPoint call) {String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println("开始执⾏:"+className+"."+methodName+"()⽅法...");}//访问命名切⼊点来应⽤后置通知@AfterReturning("allMethod()")public void afterReturn(JoinPoint call) {String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()⽅法正常执⾏结束...");}//应⽤最终通知@After("allMethod()")public void after(JoinPoint call) {String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()最终执⾏步骤(finally)...");}//应⽤异常抛出后通知@AfterThrowing("allMethod()")public void afterThrowing(JoinPoint call) {String className = call.getTarget().getClass().getName();String methodName = call.getSignature().getName();System.out.println(className+"."+methodName+"()⽅法抛出了异常...");}//应⽤周围通知//@Around("allMethod()")public Object doAround(ProceedingJoinPoint call) throws Throwable{Object result = null;this.before(call);//相当于前置通知try {result = call.proceed();this.afterReturn(call); //相当于后置通知} catch (Throwable e) {this.afterThrowing(call); //相当于异常抛出后通知throw e;}finally{this.after(call); //相当于最终通知}return result;}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
基于Spring和AOP的数据库认证日志的设计与实现
作者:陈焕英,马静婕
来源:《电脑知识与技术》2011年第09期
摘要:项目开发中,类似于数据库验证、参数合法性验证、异常处理、事务控制等的业务处理方法有很多,而他们的健壮性直接影响着整个项目的健壮性。
在以前的开发中,就要反反复复地写每个业务的代码,为解决这些繁琐的方方面面的代码编写,Spring中的AOP应运而生,将程序中涉及的公共业务问题分离成一个个方面,很好地利用方面编程解决了这些问题。
关键词:Spring;AOP;数据库认证;日志管理
中图分类号:TP311文献标识码:A文章编号:1009-3044(2011)09-1982-02
Design and Implementation of Log about Database User Authentication Base on Spring and AOP CHEN Huan-ying, MA Jing-jie
(Henan Quantity Engineering Occupation College, Pingdingshan 467001, China)
Abstract: There is a lot of businesses like database authentication, parameter's validation and abnormal process in the project development. The robustness of project is affected by their robustness. Using the old development, we describe repeatedservice code. The Spring and AOP can resolve these problems. The aspect is separated from topical business in progrom, using the aspect can efficiently solve the repetitive work.
Key words: Spring;AOP;database authentication;log administration
1 概述
1.1 什么是Spring
Spring是一个开源框架,它由Rod Johnson创建。
它是为了解决企业应用开发的复杂性而创建的。
Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。
然而,Spring的用途不仅限于服务器端的开发。
从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。
Spring框架是一个分层架构,由 7 个定义良好的模块组成[1]。
Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式,如图1所示。
组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。
每个模块的功能如下:
1) 核心容器:核心容器提供 Spring 框架的基本功能。
2) Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。
3) Spring AOP:Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。
4) Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。
5) Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具。
6) Spring Web 模块:Web上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。
7) Spring MVC 框架:MVC框架是一个全功能的构建 Web 应用程序的 MVC 实现。
1.2什么是AOP[2]
AOP——Aspect Oriented Programming, 简称AOP,面向方面/切面的编程。
AOP是一种编程模式,提供从另一个角度来考虑程序结构以完善面向对象编程(OOP)。
AOP为开发者提供了一种描述横切关注点的机制,并能够自动将横切关注点织入到面向对象的软件系统中,从而实现了横切关注点的模块化。
日志、事务、安全验证等这些通用的、散步在系统各处的需要在实现业务时关注的事情就称为“方面”,也称为“关注点”。
2 AOP的实现原理
项目开发中一般的业务处理有记录日志,合法性检验等。
1) 将业务系统中这些日志、事务、安全验证等操作分离为单个的方面,集中处理,如图2所示。
实现特定功能的方面代码在AOP概念中又称为“通知(Adivice)”,通知分为前置通知、后置通知、环绕通知和异常通知。
前置通知是在业务执行前自动执行的通知;后置通知是在业务执行后自动执行的通知;环绕通知能力最强,它可以在业务调用前执行通知代码,可以决定是否还调用目标方法;异常通知是业务方法抛出异常时自动执行的方面代码。
2) 讲方面分离出后,就专一的开发业务功能代码。
3) 通过Spring的代理方式将方面(即通知)织入到业务对象中。
AOP实现原理如图3所示。
3 以项目开发中的数据库登录验证日志管理为例讲解Spring与AOP的实现及运用
1) 数据库登录用户业务关键代码如示例1所示:
示例1:
public class UserBiz {
public User login(User user){
UserDao userDao=new UserDao();
User userg=userDao.login(user);
return userg;
}}
2) 使用前置通知实现方面代码如示例2所示:
示例2:
public class LogAdvice implements MethodBeforeAdvice {
private static DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss 秒");
public void before(Method m, Object[] args, Object target)
throws Throwable {
//Method m:被通知目标方法对象
//Object[] args:传入被调方法的参数
//Object target:被调方法所属的对象实例
System.out.println("\n[系统日志][" + sdf.format(new Date()) + "]"
+ m.getName()
+ "("+ Arrays.toString(args) + ")"
+" the method belong to "+target.getClass().getName());
}}
3) 使用Spring代理将方面代码织入业务对象中,关键代码如示例3所示:
示例3:
class="org.Springframework.aop.framework.ProxyFactoryBean">
aop.BookBiz
logAdvice
afterAdvice
aroundAdvice
ExcepAdvice
4 总结
无论是业务方法中,还是调用业务方法的代码中,都看不到日志代码的蛛丝马迹,可运行的时候,确实输出了日志代码(用户登录过)的信息。
通过使用Spring AOP,我们将日志代码分离出去,基本上不需要改动原来的代码,通过简单的配置,业务系统就具备了日志的能力。
这样很好的提高了代码的重用性,这也就是Spring AOP备受大家欢迎的原因所在。
参考文献:
[1] 陈天河.struts、hibernate、Spring集成开发宝典[M].北京:电子工业出版社,2007:488.
[2] 徐袛祥.开发基于Struts+Spring+Hibernate的网上交易系统[M].北京:科学技术文献技术出版社,2008,182.。