歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java注解在SSH開發中的簡單應用

Java注解在SSH開發中的簡單應用

日期:2017/3/1 9:38:36   编辑:Linux編程

在系統開發過程中,出現錯誤在所難免。雖然系統出錯時控制台也會報錯,但是因為系統控制台輸出太多,往往不能快速定位出現錯誤的功能點及原因。在此通過使用注解,結合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中定義

<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.htm

Java中介者設計模式 http://www.linuxidc.com/Linux/2014-07/104319.htm

Java 設計模式之模板方法開發中應用 http://www.linuxidc.com/Linux/2014-07/104318.htm

設計模式之 Java 中的單例模式(Singleton) http://www.linuxidc.com/Linux/2014-06/103542.htm

Copyright © Linux教程網 All Rights Reserved