(1)导入相应的jar包
<!--aop依赖包--> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency>
(2)在applicationContext.xml中配置
引入约束
xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
开启注解支持
<!-- 1.开启注解AOP -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 配置自动代理功能 -->
<aop:config proxy-target-class="true"></aop:config>
(3)自定义一个环绕通知的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) // 方法注解
@Retention(RetentionPolicy.RUNTIME) // 运行时可见
public @interface LogAnno {
String operateType();// 记录日志的操作类型
}
(4)准备一个日志的service
import java.sql.SQLException;
public interface LogtableService extends IBaseService<Logtable> {
public boolean addLog(Logtable log) throws SQLException;
}
(5)AOP主要就是面向切面编程,定义一个类通过环绕通知匹配对应的注解
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Date;
@Component
@Aspect
public class LogAopAspect {
@Autowired
private LogtableService logtableService;// 日志Service
/**
* 环绕通知记录日志通过注解匹配到需要增加日志功能的方法
*/
@Around("@annotation(cn.itsource.service.LogAnno)")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
// 1.方法执行前的处理,相当于前置通知
// 获取方法签名
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
// 获取方法
Method method = methodSignature.getMethod();
// 获取方法上面的注解
LogAnno logAnno = method.getAnnotation(LogAnno.class);
// 获取操作描述的属性值
String operateType = logAnno.operateType();
// 创建一个日志对象(准备记录日志)
Logtable logtable = new Logtable();
logtable.setOperatetype(operateType);// 操作说明
Employee user = UserContext.getUserInSession();//获取session中的user对象进而获取操作人名字
logtable.setOperateor(user.getUsername());// 设置操作人
Object result = null;
try {
//让代理方法执行
result = pjp.proceed();
// 2.相当于后置通知(方法成功执行之后走这里)
logtable.setOperateresult("正常");// 设置操作结果
} catch (SQLException e) {
// 3.相当于异常通知部分
logtable.setOperateresult("失败");// 设置操作结果
} finally {
// 4.相当于最终通知
logtable.setOperatedate(new Date());// 设置操作日期
logtableService.addLog(logtable);// 添加日志记录
}
return result;
}
}