【问题标题】:How can I send annotation value into @Before method?如何将注释值发送到 @Before 方法?
【发布时间】:2019-12-06 12:22:40
【问题描述】:

我想更改使用我的自定义注释注释的方法的主体。

  1. 我创建了我的自定义注释:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface RunAsUser {
    }
    
  2. 我已经编写了特殊的处理程序:

    @Aspect
    @Component
    public class RunAsUserAnnotationHandler {
    
        @Before("@annotation(RunAsUser)")
        public void configureAuthentication() {
              AuthenticationUtil.configureAuthentication("ROLE_USER");
        }
    
        @After("@annotation(RunAsUser)")
        public void clearAuthentication() {
            AuthenticationUtil.clearAuthentication();
    
       }
    }
    

    其中configureAuthentication(...)clearAuthentication() 是将另一个硬编码的主体值设置为SecurityContext 并将一个返回到默认值的方法。

如果我想在注释中将主体值设置为字符串,我该如何修改我的代码?

我想看到这样的东西:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface RunAsUser {
        String userName();
    }

并使用RunAsUser("stackoverflowUser") 编写我的代码,但我现在知道如何将此值从注释传输到我的configureAuthentication 方法。

有什么建议吗?

【问题讨论】:

    标签: java spring annotations aop


    【解决方案1】:

    RunAsUser 类型的参数添加到您的configureAuthentication() 方法。从此参数中获取值(“stackoverflowUser”):

    @Before("@annotation(runAs)")
    public void configureAuthentication(RunAsUser runAs) {
          // do something with runAs.value()
    }
    

    【讨论】:

    • 这个答案不正确。对于注解参数绑定,您需要使用参数名称,而不是切入点中的类名称。所以解决方案将是您的示例代码中的@annotation(runAs)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多