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中定义

<bean id="exceptionInterceptor" class="com.util.ExceptionInterceptor">
		<property name="sessionFactory" ref="sessionFactory" />
</bean>
用法:

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



运行这个方法时,系统就会报错:

产生错误的类:类名
<pre name="code" class="java">产生异常的方法:test
出错行数:相应的行数(当前是90)
异常类型:RuntimeException
错误信息:出现了一个错误


是不是很直观呢?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章