0

I am trying to implement custom annotation in spring as follows:- Test annotation is as follows

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

And for validation I have written CheckUser class as follows::-

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;
}

But its not working. Can some one tell me what is wrong here??

In security as well as application context I have written

<Secured:global-method-security secured-annotations="enabled" pre-post-annotations="enabled" jsr250-annotations="enabled"/>
user3640507
  • 65
  • 1
  • 7
  • And how is a custom annotation for validation related to security? Those are two completely different things. – M. Deinum Jun 04 '14 at 05:27
  • Is there any other method through which I can write custom annotation for checking user Roles other than @Secured? – user3640507 Jun 04 '14 at 05:41
  • `@RolesAllowed` from the JSR-250. or `@PreAuthorize` from Spring Security. – M. Deinum Jun 04 '14 at 05:42
  • Yes But it requires Autowired and When we call those method by creating object using "new" at that time it doesnt work. I want to implement annotation which will work even if methods are invoke by its own object. So is there any options? – user3640507 Jun 04 '14 at 05:53
  • That also still applies with custom annotations, also why roll your own? Spring Security can also work with AspectJ if you apply the security aspects at compile time Spring Security will work just fine. – M. Deinum Jun 04 '14 at 05:57
  • I am new to spring and dont know much about aspectJ can you give me link of any useful document or simple example will be really helpful – user3640507 Jun 04 '14 at 06:05
  • Thanks Denium but didnt got much about aspectJ and still stuck – user3640507 Jun 04 '14 at 06:58
  • See http://stackoverflow.com/questions/901632/why-doesnt-aspectj-compile-time-weaving-of-springs-configurable-work. And see http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#aspectj – M. Deinum Jun 04 '14 at 07:01
  • Thanks Denium for u r help – user3640507 Jun 04 '14 at 08:09

1 Answers1

0

You need to include message, groups, and payload so it plays nicely with regards to the JSR-303 spec: 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 {};
}
DavidA
  • 3,984
  • 5
  • 25
  • 38