切面类:
package com.aop;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AllLogAdvice {
private Logger logger = Logger.getLogger(AllLogAdvice.class);
// @Pointcut("execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
// @Pointcut("within(com.test.spring.aop.pointcutexp..*)")
// @Pointcut("this(com.test.spring.aop.pointcutexp.Intf)")
// @Pointcut("target(com.test.spring.aop.pointcutexp.Intf)")
// @Pointcut("@within(org.springframework.transaction.annotation.Transactional)")
// @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
// @Pointcut("args(String)")
@Pointcut("execution(* com.service.UserService.add*(..)) || execution(* com.service.UserService.delete*(..))")
public void pointcut1() {
// 定义一个pointcut,下面用Annotation标注的通知方法可以公用这个pointcut
System.out.println("************erery invoke");
}
// 前置通知
// 拦截参数为一个String类型的方法
@Before("pointcut1() && args(temp)")
public void myBeforeAdvice(String temp) {// 如果需要知道拦截的方法的信息,也可以需添加JoinPoint参数
String logInfoText = "这是前置通知" + temp;
// 将日志信息写入配置的文件中
logger.info(logInfoText);
}
// 后置通知
// 拦截 返回类型为String 的方法
@AfterReturning(pointcut = "pointcut1()", returning = "result")
public void myAfterReturnAdvice(String result) {
logger.info("这是后置通知 " + " result: " + result);
}
// 最终置通知
@After("execution(* com.service.**.*(..))")
public void doAfter() {
logger.info("这是最终通知");
}
// 异常通知
@AfterThrowing(pointcut = "pointcut1()", throwing = "e")
public void myThrowingAdvice(JoinPoint jionpoint, Exception e) {
// 获取被调用的类名
String targetClassName = jionpoint.getTarget().getClass().getName();
// 获取被调用的方法名
String targetMethodName = jionpoint.getSignature().getName();
// 日志格式字符串
String logInfoText = "异常通知:执行" + targetClassName + "类的"
+ targetMethodName + "方法时发生异常";
// 将日志信息写入配置的文件中
logger.info(logInfoText);
}
// 环绕通知
// @Around(value="pointcut1()")
@Around("pointcut1()")
public Object myAroundAdvice(ProceedingJoinPoint jionpoint)
throws Throwable {
// 获取被调用的方法名
String targetMethodName = jionpoint.getSignature().getName();
//Object o = jionpoint.proceed();
String logInfoText = "这是环绕通知:" + targetMethodName;
logger.info(logInfoText);
Object o = jionpoint.proceed();//注意写到这儿的话,环绕通知和其它通知的顺序
return o;
}
}
配置文件:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
业务接口和实现类:
package com.service;
public class UserService implements IUserService {
public int addUser(String name, int age) {
//省略诸如操作数据库等复杂的逻辑操作
System.out.println("add user "+ name +" successfully");
return 1;
}
public void deleteUser(String name) {
//省略诸如操作数据库等复杂的逻辑操作
System.out.println("deleted one user named " + name);
//throw new RuntimeException("这是特意抛出的异常信息!");
}
}
package com.service;
public interface IUserService {
public int addUser(String name, int age);
public void deleteUser(String name);
}
测试类:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.IUserService;
public class MainTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("aop.xml");
IUserService userService = (IUserService) context
.getBean("myUserService");
userService.addUser("ton", 56);
userService.deleteUser("ton");
}
}
最后附上日志文件:
log4j.rootLogger=info,stdout,info,debug,error
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
log4j.appender.info.datePattern='.'yyyy-MM-dd
log4j.appender.info.Threshold = INFO
log4j.appender.info.append=true
log4j.appender.info.File=${webApp.root}/WEB-INF/logs/info.log
log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
log4j.appender.debug.datePattern='.'yyyy-MM-dd
log4j.appender.debug.Threshold = DEBUG
log4j.appender.debug.append=true
log4j.appender.debug.File=${webApp.root}/WEB-INF/logs/debug.log
log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
log4j.appender.error.datePattern='.'yyyy-MM-dd
log4j.appender.error.Threshold = ERROR
log4j.appender.error.append=true
log4j.appender.error.File=${webApp.root}/WEB-INF/logs/error.log