gpt4 book ai didi

java - Spring AOP 和注释在方法执行之前检查参数

转载 作者:行者123 更新时间:2023-12-02 13:29:13 29 4
gpt4 key购买 nike

如果方法参数是特定值,我必须抛出异常。目的是锁定所有与特定值一起工作的方法,所以我想使用 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");
}

但参数必须是签名中的第一个

最佳答案

您可以使用可以访问调用数据的@Around建议。

@Around("@annotation(TestAOPAnnotation)")
public Object logAOP(ProceedingJoinPoint aPoint) throws Throwable {
// First, implement your checking logic
// aPoint.getArgs() may be inspected here ...
if (...) {
throw new RuntimeException(...);
}

// now, actually proceed with the method call
return aPoint.proceed();
}

getArgs() 使您可以访问传递给该方法的实际参数。

关于java - Spring AOP 和注释在方法执行之前检查参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43250409/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com