Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Java注解在SSH开发中的简单应用

在系统开发过程中,出现错误在所难免。虽然系统出错时控制台也会报错,但是因为系统控制台输出太多,往往不能快速定位出现错误的功能点及原因。在此通过使用注解,结合spring的AOP,来制作一个错误输出拦截器。首先写一个注解类Catcher:@Target({ ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface Catcher {    String name();//模块名}
然后定义一个切面:ExceptionInterceptor@Aspectpublic 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中定义<bean id="exceptionInterceptor" class="com.util.ExceptionInterceptor">        <property name="sessionFactory" ref="sessionFactory" /></bean>用法:因为在拦截器中拦截的是service层的方法(当然也可以拦截其它地方),所以对于需要拦截的方法,都要加上@Catcher注解。@Catcher(name="需要捕获错误的模块")public void test(){    throw new RuntimeException("此模块抛出异常");}运行这个方法时,系统就会报错:
产生错误的类:类名
产生异常的方法:test
出错行数:相应的行数
异常类型:RuntimeException
错误信息:出现了一个错误是不是很直观呢?大话设计模式(带目录完整版) PDF+源代码 http://www.linuxidc.com/Linux/2014-08/105152.htmJava中介者设计模式 http://www.linuxidc.com/Linux/2014-07/104319.htmJava 设计模式之模板方法开发中应用 http://www.linuxidc.com/Linux/2014-07/104318.htm设计模式之 Java 中的单例模式(Singleton) http://www.linuxidc.com/Linux/2014-06/103542.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-10/108301.htm