【发布时间】:2017-04-06 08:57:50
【问题描述】:
如果方法参数是特定值,我必须抛出异常。 目的是锁定所有使用特定值的方法,所以我想使用 Spring AOP,但我是新手。 我的问题是检索方法参数的值,我创建了这个示例:
注释
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAOPAnnotation {
}
AOP 类
@Component
@Aspect
public class TestAOP {
@Before("@annotation(TestAOPAnnotation)")
public void logAOP(){
//Make some operations with database and throw exception in a specific case
throw new RuntimeException();
}
}
我使用注解的方法
@Override
@TestAOPAnnotation
public List<Animals> findByName(String name) throws QueryException {
try{
return animalsRepository.findByName(name);
}catch(Exception e){
throw new QueryException(e);
}
}
我发现异常的地方
@Override
@RequestMapping(value="/test/{name}", method = RequestMethod.GET)
public @ResponseBody List<Animals> findByName(@PathVariable String name){
try{
return databaseAnimalsServices.findByName(name);
}catch(QueryException e){
return null;
}catch(Exception e){
//CATCH AOP EXCEPTION
List<Animals> list = new ArrayList<Animals>();
list.add(new Animals("AOP", "exception", "test"));
return list;
}
}
如何获取名称参数?我可能会在参数上使用另一个注释(或仅此注释),但我不知道如何。你能帮帮我吗?
编辑 要捕获参数注释,我可以使用:
@Before("execution(* *(@Param (*),..))")
但它只有在我知道参数顺序时才有效,而我只需要带注释的参数。 否则,到目前为止,最好的解决方案是
@Before("@annotation(TestAOPAnnotation) && args(name,..)")
public void logAOP(String name){
System.out.println(name);
throw new RuntimeException("error");
}
但参数必须是签名中的拳头
【问题讨论】:
标签: java spring annotations aop spring-aop