我有一个 Controller :
@Authorised(id = "{personId}")
@RequestMapping(value = {"{personId}"}, method = GET)
public void test(@PathVariable PersonId personId) {
System.out.println(personId); //gets personId
}
注释:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorised {
String id() default "";
}
切入点:
@Pointcut("@annotation(Authorised)")
private void AuthorisedMethod() {}
必须获取 {personId} 值而不是字符串“{personId}”的方法:
@Before("AuthorisedMethod()")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint) throws NoSuchMethodException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
Parameter[] parameters = signature.getMethod().getParameters();
Authorised annotations = joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes).getAnnotation(Authorised.class);
String id = annotations.id();
System.out.println(id); // prints: "{personId}"
// do the chekcing
throw new UnauthenticatedUserException();
}
能否实现以及如何实现?
更新:但是如果方法参数参数编号与切入点 args() 不匹配怎么办?我的意思是,如果特定方法具有参数 @PathVariable PersonId personId 以及更多参数,但 pointcut 只需要知道 PersonId personId 会怎么样?
就像@statut说的,你必须这样写args():args(personId,..)
最佳答案
例如,您可以修改 @Before()
注释以具有 PersonId
值并将该值传递给方面
@Before("AuthorisedMethod() && args(personId)")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint, PersonId personId) throws NoSuchMethodException {}
为了测试它,我有以下方面:
@Aspect
@Component
public class SomeAspect {
@Pointcut("@annotation(Authorised)")
private void AuthorisedMethod() {
}
@Before("AuthorisedMethod() && args(personId)")
public void checkIfIsCurrentlyAuthenticated(JoinPoint joinPoint, PersonId personId) throws NoSuchMethodException {
System.out.println("aspect " + personId.getId());
}
}
配置类:
@Configuration
@ComponentScan(basePackages = {"test"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Config {
}
测试组件:
@Component
public class Test {
@Authorised(id = "{personId}")
public void test(PersonId personId) {
System.out.println("component " + personId.getId()); //gets personId
}
}
以及 testNG 的运行程序:
@ContextConfiguration(classes = Config.class)
public class TestRunner extends AbstractTestNGSpringContextTests {
@Autowired
test.Test test;
@Test
public void testName() {
test.test(new PersonId("id"));
}
}
当我运行它时,我会从方面打印“aspect id”
,并从调用的方法打印“component id”
。
关于java - 如何获取自定义注释的@PathVariable值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48900910/