给出一个带有
的Spring Boot应用程序AspectJConfiguration:
@Configuration
@EnableAspectJAutoProxy
public class AspectJConfiguration {
}
方面:
@Aspect
public class DataAccessExceptionAspect implements ThrowsAdvice {
@AfterThrowing(pointcut = "execution(* com.acme.dao.*(..))",
throwing = "e")
public void afterThrowing(JoinPoint joinPoint,
DataAccessException e) throws Throwable {
// do something
throw new AppSpecificCustomException();
}
}
DAO:
package com.acme.dao;
// etc...
@Repository
public class WidgetDAO {
@Autowired NamedParameterJdbcTemplate jdbcTemplate;
// etc...
public Widget getWidget(Long widgetId) {
// etc...
return jdbcTemplate.queryForObject(sql, paramMap, rowMapper);
}
}
NamedParameterJdbcTemplate.queryForObject抛出DataAccessException。
我希望当getWidget()传递一个不存在的widgetId时,会抛出一个DataAccessException(特别是EmptyResultDataAccessException)并且Aspect会抓住它。抛出异常,但方面永远不会看到它。我已经尝试将方面的签名更改为:
public void afterThrowing(JoinPoint joinPoint,
EmptyResultDataAccessException e) throws Throwable
并没有什么区别。
答案 0 :(得分:0)
我通过进行2次更改解决了这个问题。
1)方面需要由Spring管理。添加@Component注释可以解决这个问题。
2)切入点定义错误。它应该是com.acme.dao.WidgetDAO。*
@Component // @Component annotation is required
@Aspect
public class DataAccessExceptionAspect implements ThrowsAdvice {
@AfterThrowing(pointcut = "execution(* com.acme.dao.WidgetDAO.*(..))",
throwing = "e")
public void afterThrowing(JoinPoint joinPoint,
DataAccessException e) throws Throwable {
// do something
throw new AppSpecificCustomException();
}
}