Simon Oelerich opened SPR-16964 and commented

Creating an ControllerAdvice with assignableTypes works fine.

Custom annotations are not recognized as follows:

@ControllerAdvice(annotations = AdminsOnly.class)
public class AdminControllerAdvice { ... }
@Controller
@AdminsOnly
public AdminController { ... }
public @interface AdminsOnly { }

With this type of ControllerAdvice the AdminController will not use the advice.


The following is working fine as a workaround:

@ControllerAdvice(assignableTypes = AdminsOnly.class)
public class AdminControllerAdvice { ... }
@Controller
public AdminController implements AdminsOnly { ... }
public interface AdminsOnly { }

Affects: 5.0.6, 5.0.7

Comment From: spring-projects-issues

Juergen Hoeller commented

Has the custom annotation been declared with @Retention(RetentionPolicy.RUNTIME)? Any other specifics that possibly makes it different from the annotations that come with Spring? Does it work for you with a custom stereotype: e.g. an @AdminController annotation that is meta-annotated with @Controller, binding the advice to AdminController.class?

Comment From: spring-projects-issues

Simon Oelerich commented

I had no @Retention annotation and that was the problem. With @Retention(RetentionPolicy.RUNTIME) it works as expected.

The javadoc for ControllerAdvice.annotations() says:

Consider creating a special annotation or use a predefined one, like @RestController.

I was a bit surprised that there is this hint, but it won't work out of the box, as I am used to in the Spring context (mostly).

Maybe it could be added to use the RetentionPolicy RUNTIME to this part of the javadoc.

Nevertheless the mentioned @RestController uses it and I should have figured this out by myself.

I appreciate your help and thank you for the idea to create a custom @AdminController wich serves my purpose best.

  • This issue can be closed -

Comment From: fransflippo

Ran into the same issue! A hint about the retention policy in the documentation would have been really helpful.

I'll look at submitting a pull request with this added to the ControllerAdvice javadoc.