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

来源:互联网 发布:征服者数据更新 编辑:程序博客网 时间:2024/05/04 02:58
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
原创粉丝点击