2016-02-13 63 views
0

我想捕获在我的应用程序中发生的所有异常/错误。
因此,我搜索了stackoverflow,并在这个问题上遇到了问题:Java Exception Listener
现在我想知道这是否可以以更好的方式完成。Spring Java Exception Listener without web

我当前的应用程序:
我使用与Spring JPA Spring框架在独立代码没有 Web组件。我有一个Config.java文件有四个主要的豆类:

  • 时间韦弗
  • 数据源
  • 实体管理器工厂
  • 事务管理

现在我认为我可能会使用的东西如下所示:

package me.test; 

import java.beans.ExceptionListener; 
import org.springframework.stereotype.Component; 

@Component 
public class ErrorListener implements ExceptionListener { 
    @Override 
    public void exceptionThrown(Exception e) { 
     System.out.println("Some error occured ... That's bad :("); 
    } 
} 

我不确定这ExceptionListener是否像我想让他工作一样,所以我想也许有人可以向我解释,如果我想要的可能或不可能。
也许不是用这个监听器,而是用其他方法?

另外还有其他一般问题:
我该如何注册一个听众?是不是也有一个@EventListener诠释?我是否必须在一个方法之前放置它,然后让它作为Component的一部分通过弹簧进行扫描?
或者我必须在我的上下文中手动注册吗?

谢谢:)

---编辑---

AfterThrowing这个想法似乎很不错(见下面的评论)。现在我的项目是这样的:

在主

new AnnotationConfigApplicationContext(Config.class); 

Config.java

@EnableTransactionManagement 
@ComponentScan("me.test.*") 
@Configuration 
@EnableJpaRepositories 
@EnableAspectJAutoProxy 
public class Config { 
    @AfterThrowing(pointcut = "execution(public * *(..)", throwing = "ex") 
    public void doRecoveryActions(DataAccessException ex) { 
     System.out.println("Error found"); 
    } 
    /* loadTimeWeaver, dataSource, entityManagerFactory and transactionManager with the "@Bean" annotation */ 
} 

,然后在随机文件的东西,抛出一个错误,如int i2 = 5/0;,并在其他级别throw new Exception("test");
但不幸的是它也没有工作:(
我在做什么错?

回答

1

你可以使用Spring AOP的建议这个地方,你会抛出建议后使用。

+0

我已经想过这个问题,但' @ Around'需要一个函数作为参数,那么我怎么才能完成一个函数,这个函数在抛出异常时执行,无论在哪里? – christopher2007

+1

你可以做的是如下 @Aspect public class AfterThrowingExample { @AfterThrowing( pointcut="execution(public * *(..)", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // ... } }

+0

基本上如果有公共方法抛出异常执行建议方法。您可以根据您的要求更改切入点 –