【问题标题】:Custom Annotation in spring春季自定义注解
【发布时间】:2014-06-04 04:47:23
【问题描述】:

我正在尝试在 spring 中实现自定义注释,如下所示:- 测试注解如下

@Documented
@Target( { ElementType.METHOD, ElementType.FIELD })
@Constraint(validatedBy=CheckUser.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
String user();
}

为了验证,我编写了 CheckUser 类如下::-

private String xyz;
@Override
public void initialize(Test user) {
xyz=user.toString();
}

@Override
public boolean isValid(Principal principal, ConstraintValidatorContext context) {
if(principal.getName().equalsIgnoreCase(xyz))
return true;
else
return false;
}

但它不起作用。谁能告诉我这里出了什么问题??

我写过的安全和应用程序上下文

<Secured:global-method-security secured-annotations="enabled" pre-post-annotations="enabled" jsr250-annotations="enabled"/>

【问题讨论】:

  • 那么自定义注解如何与安全性相关?这是两个完全不同的东西。
  • 除了@Secured 之外,还有其他方法可以让我编写自定义注释来检查用户角色吗?
  • @RolesAllowed 来自 JSR-250。或来自 Spring Security 的 @PreAuthorize。
  • 是的,但是它需要 Autowired 并且当我们通过使用“new”创建对象来调用这些方法时,它不起作用。我想实现即使方法由自己的对象调用也能工作的注释。那么有什么选择吗?
  • 这也仍然适用于自定义注释,为什么还要自己滚动?如果您在编译时应用安全方面,Spring Security 也可以与 AspectJ 一起使用 Spring Security 可以正常工作。

标签: spring spring-security spring-annotations


【解决方案1】:

您需要包含消息、组和有效负载,这样它才能很好地符合 JSR-303 规范:http://beanvalidation.org/1.0/spec/#constraintsdefinitionimplementation-constraintdefinition-properties

@Documented
@Target( { ElementType.METHOD, ElementType.FIELD })
@Constraint(validatedBy=CheckUser.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {

    String user();

    String message() default "test failed"

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 2015-07-30
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多