aop的依赖:
org.springframework.boot
spring-boot-starter-aop
注解类:
import java.lang.annotation.Documented;
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)
@Documented
public @interface LogAnno {
//要执行的操作类型比如:添加,修改等
public String operationType() default "";
//要执行的具体操作比如:添加文件等
public String operationName() default "";
}
切面类:
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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 org.springframework.web.bind.annotation.RequestMapping;
import com.sinosoft.security.dao.LoggerMapper;
import com.sinosoft.security.po.Logger;
import com.sinosoft.security.po.extend.UserExtend;
@Component
@Aspect //切面类
public class LogAspect {
@Autowired
private HttpServletRequest request;
@Autowired
private LoggerMapper loggerMapper;
//环绕通知 包名 类名 方法名 参数
@Around("execution(* com.sinosoft.*.controller.*.*(..))")
public Object around(ProceedingJoinPoint point) throws Throwable{ //参数是目标方法
try {
String typeName="";
String locat="";
Signature signature = point.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
//获取当前执行的方法
Method targetMethod = methodSignature.getMethod();
//获取当前用户信息
UserExtend eUser = (UserExtend) request.getSession().getAttribute("CURRENT_USER_INFO");
**//判断是否具有LogAnno注解**
if (targetMethod.isAnnotationPresent(LogAnno.class)) {
typeName=targetMethod.getAnnotation(LogAnno.class).operationType();
locat=targetMethod.getAnnotation(LogAnno.class).operationName();
**//实体类**
Logger logger=new Logger();
logger.setCreateTime(new Date());
logger.setUserid(eUser.getId());
logger.setOrgid(eUser.getOrgid());
logger.setOpType(typeName);
logger.setLocation(locat);
loggerMapper.insertSelective(logger);
}
} catch (Exception e) {
e.printStackTrace();
}
return point.proceed(); //代理方法的返回值
}
}
spring开启对aop的支持
controller实列:
@RequestMapping(method = RequestMethod.POST,value = “updateOrganization”)
@ResponseBody
@LogAnno(operationType=“修改”,operationName=“修改日志”)
public AjaxResult updateOrganization(Organization organizatio){
AjaxResult result = organizationService.updateOrganization(organizatio);
return result;
}