spring使用AOP和自定义注解功能添加日志管理--实用

1、首先创建注解Log类:

@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Log {

public String operationType() default "";  

public String operationName() default "";
}

2、创建Aspect切面类SystemLogAspect

@Aspect   //此处注解需要在springMVC xml配置文件设置
@Component
public class SystemLogAspect {

private   static   final Logger logger = Logger.getLogger(SystemLogAspect. class);

public SystemLogAspect(){
System.out.println("**************SystemLogAspect****************");
}
@Pointcut("@annotation(com.iflytek.epdcloud.  
public   void controllerAspect() {
}

private String getUserNamer(){
String username="";
HttpServletRequest request = ((ServletRequestAttributes )RequestContextHolder.getRequestAttributes()).getRequest();
username =request.getSession().getAttribute(Const.SESSION_USERNAME).toString();
return username;
}


 
@Before("controllerAspect()")
public void before(JoinPoint joinPoint) {
logger.info("开始before>>>>>" + joinPoint);
logger.info("username>>>>>"+getUserNamer());
logger.info("type>>>>>"+getType(joinPoint));
logger.info("name>>>>>"+getName(joinPoint));
}     

 
@After("controllerAspect()")  
public   void after(JoinPoint joinPoint) {
logger.info("username>>>>>"+getUserNamer());
logger.info("type>>>>>"+getType(joinPoint));
logger.info("name>>>>>"+getName(joinPoint));
logger.info("结束after>>>" + joinPoint);
}


@AfterThrowing("controllerAspect()")
public void error(JoinPoint joinPoint){
logger.info("抛出异常error>>>" + joinPoint);
logger.info("username>>>>>"+getUserNamer());
logger.info("type>>>>>"+getType(joinPoint));
logger.info("name>>>>>"+getName(joinPoint));
}

private String getName(JoinPoint joinPoint) {  
MethodSignature methodName = (MethodSignature)joinPoint.getSignature();  
Method method = methodName.getMethod();  
return method.getAnnotation(Log.class).operationName();  

private String getType(JoinPoint joinPoint) {  
MethodSignature methodName = (MethodSignature)joinPoint.getSignature();  
Method method = methodName.getMethod();  
return method.getAnnotation(Log.class).operationType();  

}
3、在springMVC 配置文件xml配置相关参数如下;


4、在controller类使用实例说明:
@Log(operationType=Const.QUERY,operationName="获取用户对象")
@RequestMapping(value="/getUserById/{id}",method=RequestMethod.GET)
public PageData getUserById(@PathVariable("id") String id) throws Exception{
PageData pd = this.getPageData();
pd.put("USER_ID", id);
return   userService.findById(pd);
}
5、运行效果如下图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值