Spring 未调用方面
Spring Aspect Not Called
给定 Spring 引导应用程序
AspectJ配置:
@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
并没有什么区别。
我通过进行 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();
}
}
给定 Spring 引导应用程序
AspectJ配置:
@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
并没有什么区别。
我通过进行 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();
}
}