Reputation: 620
I'm looking to create a custom annotation designed to check whether a user is authorized to act on a certain product ID. The annotation would be placed on methods in my controller, which is run in a Spring managed application.
@ProductDemand(id = {productId})
@RequestMapping(value = "/product/{productID}", method = RequestMethod.PUT)
public Product update(Product toUpdate) {
User user = getUserFromHeaderValues();
}
In this scenario the @ProductDemand is the custom annotation I will be needing to create. If the user is not authorized to act on a product with given ID, I'd like to return a 403.
What I have so far is an annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ProductDemand {
String productId;
}
I also have a service to authorize those values:
public class AuthorizationService {
public boolean authorize(UUID userUUID, String productID) {
//do auth
}
}
What I would like to do is be able to put that annotation on any method and have it automatically call the authorize method in AuthorizationService. Obviously there will be some plumbing in between to get the values and hook up the authorization service, but I don't currently know how to do that. Preferably, I'd like to be able to jar all of this up, and allow someone to be able to import it into their project and be able to use it just by adding annotations as well and maybe a bean if necessary.
I've never written any custom annotations before so if this makes no sense please let me know.
Thanks, Phil
Upvotes: 2
Views: 5257
Reputation: 34424
Use the spring aspects where you can use pointcut with your custom annotation. Then you can apply advice either before,after, around etc. This is what you want
Here is the example @AspectJ pointcut for all methods of a class with specific annotation
Upvotes: 1