javascript
SpringAOP Aspect注解实现简单日志功能
SpringAOP實(shí)現(xiàn)簡(jiǎn)單日志功能
AOP(Aspect Oriented Programming):面向切面編程,Spring框架的重要組成部分,利用AOP我們可以將一些公用的業(yè)務(wù)邏輯部分抽取出來(lái),動(dòng)態(tài)的插入到程序中(如日志記錄、權(quán)限控制等),降低了各業(yè)務(wù)邏輯的耦合度。
關(guān)于AOP的相關(guān)概念這里就不進(jìn)行講解了,不了解的可以自行學(xué)習(xí)下,這里為了方便理解下面代碼簡(jiǎn)單講解幾個(gè)概念:
在開始前首先我們需要在pom.xml中引入一些相關(guān)的jar。
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.7.4</version> </dependency> <dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.7.4</version> </dependency> <dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.1</version> </dependency>進(jìn)入代碼環(huán)節(jié),創(chuàng)建一個(gè)切面類LogAspect ,如下:
@Component @Aspect public class LogAspect {/*** 切入點(diǎn),使用方法切點(diǎn)函數(shù)execution匹配* * com.xxx.aop.test..*.*(..):表示test包和所有子包里的任意類的任意方法*/@Pointcut("execution(* com.xxx.aop.test..*.*(..))")public void logPointcut(){}/*** 后置通知,JointPoint執(zhí)行完成后執(zhí)行,不論是否JointPoint異常,實(shí)質(zhì)是finally中的代碼塊* @param joinPoint*/@After("logPointcut()")public void doAfter(JoinPoint joinPoint){Object[] args = joinPoint.getArgs(); // 參數(shù)值String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames(); // 參數(shù)名String methodName = joinPoint.getSignature().getName(); // 獲取方法名HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String ip = request.getRemoteAddr(); // 獲取IP地址HttpSession session = request.getSession();User user = (User)session.getAttribute("userCache");//獲取用戶,根據(jù)自身項(xiàng)目實(shí)際情況修改//保存日志System.out.println("執(zhí)行保存日志操作...");} }@After注解的方法是在JointPoint執(zhí)行完以后執(zhí)行,如果需要在JointPoint執(zhí)行前執(zhí)行某些操作,可以使用@Around注解,使用方法如下:
/*** 環(huán)繞通知,在JointPoint執(zhí)行完成前后執(zhí)行* @param pjp* @return* @throws Throwable*/@Around("logPointcut()")public Object doAround(ProceedingJoinPoint pjp) throws Throwable{//切入方法執(zhí)行前的操作System.out.println("LogAop Before Advice...");//執(zhí)行joinPointObject obj=pjp.proceed();//切入方法執(zhí)行后的操作System.out.println("LogAop After Advice...");//必須返回執(zhí)行結(jié)果,不返回會(huì)出現(xiàn)404等錯(cuò)誤return obj;}Spring和SpringMVC的配置文件中都進(jìn)行如下配置:
<!-- 注意自己的配置中是否存在下面的配置,如果有就無(wú)需再配置 --><!-- xml命名空間的聲明 --> xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation= "http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd" <!-- 開啟aspectj注解 --> <aop:aspectj-autoproxy />SpringMVC是Spring的一個(gè)子容器,為了解決事務(wù)失效問(wèn)題,我們通常會(huì)配置在Spring容器中不掃描@Controller注解,在SpringMvc容器中只掃描@Controller注解。因此,如果不需要切入Controller的話SpringMVC配置文件就不需要進(jìn)行配置,反之,只切入Controller就不需要配置Spring配置文件。
到此為止,一個(gè)簡(jiǎn)單的日志切面就完成了,日志記錄了用戶、訪問(wèn)IP、訪問(wèn)方法等信息,但用戶并不能通過(guò)查看日志中的訪問(wèn)方法知道是操作的哪個(gè)菜單,下篇文章講解[SpringAOP+自定義注解實(shí)現(xiàn)日志功能]。
總結(jié)
以上是生活随笔為你收集整理的SpringAOP Aspect注解实现简单日志功能的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python精要(81)-collect
- 下一篇: gradle idea java ssm