设为首页 加入收藏

TOP

Java注解在SSH开发中的简单应用
2014-11-23 19:33:54 】 浏览:308
Tags:Java 注解 SSH 开发 简单 应用

在系统开发过程中,出现错误在所难免。虽然系统出错时控制台也会报错,但是因为系统控制台输出太多,往往不能快速定位出现错误的功能点及原因。在此通过使用注解,结合spring的AOP,来制作一个错误输出拦截器。


首先写一个注解类Catcher:


@Target({ ElementType.METHOD })


@Retention(RetentionPolicy.RUNTIME)


@Documented


@Inherited


public @interface Catcher {


String name();//模块名


}



然后定义一个切面:ExceptionInterceptor


@Aspect


public class ExceptionInterceptor {


private Logger logger = Logger.getLogger(ExceptionInterceptor.class);


/**


* 拦截service层带有Catcher注解的所有异常


* @param point


* @param cat


* @param ex


*/


@AfterThrowing(pointcut="execution(* com.*.service.*.*(..))&&@annotation(cat)",throwing="ex")


public void serviceSite(JoinPoint point,Catcher cat,Throwable ex){


StackTraceElement st=ex.getStackTrace()[0];


logger.error("产生错误的模块:"+cat.name());


logger.error("产生错误的类:"+point.getTarget().getClass().getSimpleName());


logger.error("产生异常的方法:"+point.getSignature().getName());


logger.error("出错行数:"+st.getLineNumber());


logger.error("异常类型:"+ex.getClass().getName());


logger.error("错误信息:"+ex.getMessage());


}


}


注:ExceptionInterceptor需要在spring.xml中定义





用法:


因为在拦截器中拦截的是service层的方法(当然也可以拦截其它地方),所以对于需要拦截的方法,都要加上@Catcher注解。


@Catcher(name="需要捕获错误的模块")


public void test(){


throw new RuntimeException("此模块抛出异常");


}


运行这个方法时,系统就会报错:
产生错误的类:类名
产生异常的方法:test
出错行数:相应的行数
异常类型:RuntimeException
错误信息:出现了一个错误


是不是很直观呢?


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇S3C2440 MPLL & UPLL 下一篇S3C2410 MMU(存储器管理单元)详..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目