I have created a java 17 repeatable annotation and want to create an aspect around the method containing the annotation is invoked. This seems to work when method is annotated once but fails to invoke when I have repeatable annotation. I am using aspectjrt version 1.9.7. Am I doing something wrong or aspect doesn't support repeatable annotations? Any workaround for the same?
Annotation class ->
#Repeatable(Schedules.class)
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 12;
}
The repeatable class ->
#Retention(value = RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Schedules {
Schedule[] value();
}
The aspect class ->
#Aspect
#Component
#Slf4j
public class Aspect {
#Around("#annotation(Schedule)")
public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Schedule filters = method.getAnnotation(Schedule.class);
//Business Logic
return joinPoint.proceed();
}
}
This actually is not an AOP problem, but you need to understand how repeatable annotations work in Java: If the annotation appears multiple times on the annotated element, it is not represented as a single annotation anymore but as an array of annotations in the value() of the annotation type mentioned in #Repeatable, i.e. in your case #Schedules (plural "s"!).
For your aspect, it means that you need two pointcuts, one for the single-annotation case and one for the multi-annotation one. I am suggesting to factor out the common advice code into a helper method of the aspect which always takes an array of the repeatable annotations, then just pass the value of the wrapper annotation on in one case and a one-element array in the other case.
Feel free to ask follow-up questions, if anything is unclear. But it should be straightforward, almost trivial.
Resources:
https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html
https://dzone.com/articles/repeatable-annotations-in-java-8-1
P.S.: You should learn about how to bind annotations to advice method parameters:
#Around("#annotation(schedule)")
public Object traceSingle(ProceedingJoinPoint joinPoint, Schedule schedule) throws Throwable
// ...
#Around("#annotation(schedules)")
public Object traceMultiple(ProceedingJoinPoint joinPoint, Schedules schedules) throws Throwable
Related
Using spring boot 2 on java 11, I want to make a custom annotation for each REST API version (eg: "/api/v1/") that can be joined with subsequent URI components as below:
#APIv1("/users/") // this annotation should prepend "/api/v1/{argument}"
public class UserController {
#GetMapping("/info")
public String info() {return "This should be returned at /api/v1/users/info/";}
/* More methods with mappings */
}
The problem is I don't know how to define that #APIv1 annotation.
From what I've searched, I referenced https://stackoverflow.com/a/51182494/ to write the following:
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Documented
#RestController
#RequestMapping("/api/v1")
#interface APIv1 {
#AliasFor(annotation = RestController.class)
String value() default "";
}
But this cannot handle arguments. Doing the same as above will route to /api/v1/info/ whether the argument is given or not. It's better than nothing since I can switch the method annotation to #GetMapping("/users/info"), but I was wondering if there was a way to combine the constant with an argument to reduce repetition across method annotations within the same controller class.
In #APIv1 you defined:
#RequestMapping("/api/v1")
So it is working as you told it to.
i'm working with a lot of interface inherited and annotations lately and I have a doubt about #Inherited annotation. I know that by default java annotations are not inherited for subclasses and methods. Using the #Inherited annotation we can make the annotation be inherited by the subclasses.
But it also work with the annotated values in the method constructors?
For example:
#Inherited
#StringDef({ID_REAR, ID_FRONT})
#Retention(RetentionPolicy.SOURCE)
public #interface CustomId {
}
public interface Setting {
void update(#CustomId String myCustomId);
}
public class CustomSetting implements Setting{
#Override public void update(String myCustomId) {
}
}
In this case, will the method update from CustomSetting implement the annotation#CustomId for his contructor (String myCustomId) ?
As Jesper answer above, the API docs is very clear about it: The #Inherit annotation doesn't work with anything other than a class:
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.
Use load-time weaving, pure AspectJ.
We have 2 annotations #Time and #Count, and a few annotated methods.
#Time (name="myMethod1Time")
#Count (name="myMethod1Count")
public void myMethod1(){..};
#Time (name="myMethod2Time")
public void myMethod2(){..};
#Count (name="myMethod3Count")
public void myMethod3(){..};
Now I am defining my own around aspect for myMethod1 which has multiple annotations:
// multiple annotations, not working
#Around("#annotation(time) && #annotation(count))
public Object myAspect(Time time, Count count) {..}
This doesn't work. However, capture method myMethod2 works fine with a single annotation:
// single annotation, is working
#Around("#annotation(time))
public Object myAnotherAspect(Time time) {..}
I want to capture only methods with both Time and Count annotations present in their signature, and I want to use the annotation value. Anyone know how to achieve this?
Maybe combine 2 pointcuts like:
#Around("call(#Time * *(..)) && call(#Count * *(..))");
Java annotations are marked with a #Target annotation to declare possible joinpoints which can be decorated by that annotation. Values TYPE, FIELD, METHOD, etc. of the ElementType enum are clear and simply understandable.
Question
WHY to use #Target(ANNOTATION_TYPE) value? What are the annotated annotations good for? What is their contribution? Give me an explanation of an idea how it works and why I should use it. Some already existing and well-known example of its usage would be great too.
You can use an annotated annotation to create a meta-annotation, for example consider this usage of #Transactional in Spring:
/**
* Shortcut and more descriptive "alias" for {#code #Transactional(propagation = Propagation.MANDATORY)}.
*/
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Transactional(propagation = Propagation.MANDATORY)
public #interface RequiresExistingTransaction {
}
When you enable Spring to process the #Transactional annotation, it will look for classes and methods that carry #Transactional or any meta-annotation of it (an annotation that is annotated with #Transactional).
Anyway this was just one concrete example how one can make use of an annotated annotation. I guess it's mostly frameworks like Spring where it makes sense to use them.
Each annotation annotated by #Target(ElementType.ANNOTATION_TYPE) is called Meta-annotation. That means, you can define your own custom annotations that are an amalgamation of many annotations combined into one annotation to create composed annotations.
A good example from Android world is StringDef
Denotes that the annotated String element, represents a logical type and that its value should be one of the explicitly named constants.
#Retention(SOURCE)
#StringDef({POWER_SERVICE, WINDOW_SERVICE, LAYOUT_INFLATER_SERVICE})
public #interface ServicesName {}
public static final String POWER_SERVICE = "power";
public static final String WINDOW_SERVICE = "window";
public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
Code inspector will treat #ServicesName and #WeekDays in the same way as #StringDef.
As a result we can create as much named StringDef's as we need and override set of constants. #Target(ElementType.ANNOTATION_TYPE) it is a tool that allows to extend the use of annotations.
Annotation is defined like a ordinary Java interface, but with an '#' preceding the interface keyword (i.e., #interface ). Annotations are used to provide supplemental information about a program. On the other hand, an interface can be defined as a container that stores the signatures of the methods to be implemented in the code segment.
WHY to use #Target(ANNOTATION_TYPE) value?
When there is need to apply an annotation to an another annotation. If you look at the source codes of the common Java annotations, you see often this code pattern:
#Target(ANNOTATION_TYPE)
public #interface TheAnnotation
{
...
}
For example,
#Documented
#Target({ ANNOTATION_TYPE })
#Retention(RUNTIME)
public #interface Constraint {
public Class<? extends ConstraintValidator<?, ?>>[] validatedBy();
}
What are the annotated annotations good for?
They are good or more precisely necessary if they are used to annotate other annotations.
What is their contribution?
They make possible to apply an annotation directly to an another annotation, that is a different thing than applying an annotation to a standard Java class or to method and so on.
Give me an explanation of an idea how it works and why I should use it.
For example, if you create a data model class and you may want that the program checks data validity. In that case, there might be need to create a new annotation and apply another annotations to this annotation. It is simple to add some data validity checks to this model by adding annotations to the class. For example, to check that some value is not null (#notNull) or email is valid (#ValidEmail) or length of a field is more than x characters (#Size). However, it is possible that there is not built in Java annotations for all purposes. For example, it is so if you liked to check if password and its matchingPassword are same. This is possible by creating the annotation class PasswordMatches:
#Target({TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = PasswordMatchesValidator.class)
#Documented
public #interface PasswordMatches {
String message() default "Passwords don't match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Note, there is line
#Constraint(validatedBy = PasswordMatchesValidator.class).
In other words, the annotation class Constraint, like the other annotations in this class also, must have ANNOTATION_TYPE as a value of target annotation.
Now the password equality check is easy to include to data model class simply by adding annotation #PasswordMatches:
#PasswordMatches
public class UserDto {
...
}
The PasswordMatchesValidator class could look like this:
public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {
#Override
public void initialize(final PasswordMatches constraintAnnotation) {}
#Override
public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
final UserDto user = (UserDto) obj;
return user.getPassword().equals(user.getMatchingPassword());
}
}
Some already existing and well-known example of its usage would be great too.
There is quite well-known example in item 4, but another known annotations which are applied frequently to custom annotations are #Retention, #Documented and #Target itself.
For example, if annotation looks like
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface SomeAnnotation {
String description() default "This is example for class annotation";
}
the compiler will complain in this situation
#SomeAnnotation
public class SomeClass {
#SomeAnnotation // here it's complaning
public void someMethod(){}
}
If you change
#Target(ElementType.TYPE)
to
#Target({ElementType.METHOD, ElementType.TYPE})
it won't complain anymore.
Annotation are basically additional metadata (information) that goes along with your code. It can be placed along side types (Classes, Interfaces), methods, and arguments.
It is often useful during compile time and runtime. Many popular APIs such as Java EE 5+, Spring, AspectJ leverage annotation for code clarity and consistency.
Using annotation often allows code to be more readable, more easily understood.
I'd recommend you read through the annotation chapter on Java tutorial
In the past metadata are often given as an xml file, and it's difficult for someone trying to understand the code if they have to lookup a different xml configuration file. The latest Java servlet API allows mapping of servlet simply by using annotation -- as opposed of web.xml mapping:
#WebServlet("/response")
public class ResponseServlet extends HttpServlet {
// servlet code here...
}
I'd like to implement declarative security with Spring/AOP and annotations.
As you see in the next code sample I have the Restricted Annotations with the paramter "allowedRoles" for defining who is allowed to execute an adviced method.
#Restricted(allowedRoles="jira-administrators")
public void setPassword(...) throws UserMgmtException {
// set password code
...
}
Now, the problem is that in my Advice I have no access to the defined Annotations:
public Object checkPermission(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
System.out.println("Allowed:" + rolesAllowedForJoinPoint(pjp));
...
}
private Restricted rolesAllowedForJoinPoint(ProceedingJoinPoint thisJoinPoint)
{
MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();
Method targetMethod = methodSignature.getMethod();
return targetMethod.getAnnotation(Restricted.class);
}
The method above always returns null (there are no annotations found at all).
Is there a simple solution to this?
I read something about using the AspectJ agent but I would prefer not to use this agent.
To whoever is still having problem after changing annotation retention to Runtime, you might be having the same problem I had: getMethod() returns interface method instead of the implementing class. So, if you have your annotations in the class then naturally getAnnotations() on the interface method returns null.
The following solution solved this problem:
final String methodName = pjp.getSignature().getName();
final MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {
method = pjp.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
}
and if you like, you have the option of handling interface annotations here too.
Some more comments available here:
getting template method instance from ProceedingJoinPoint
Oleg
I assume #Restricted is your annotation. If that is the case, make sure you have:
#Retention(RetentionPolicy.RUNTIME)
in your annotation definition. This means that the annotation is retained at runtime.
Even after changing the retention policy like Bozho mentioned this call to get annotation returns null:
targetMethod.getAnnotation(Restricted.class);
What I found is you have to bind the annotation. Given the interface is declared like this:
#Retention(RetentionPolicy.RUNTIME)
public #interface Restricted {
String[] allowedRoles();
}
The advice would need to be declared like this:
#Before("#annotation( restrictedAnnotation )")
public Object processRequest(final ProceedingJoinPoint pjp, Restricted restrictedAnnotation) throws Throwable {
String[] roles = restrictedAnnotation.allowedRoles();
System.out.println("Allowed:" + roles);
}
What this does is bind the annotation to the parameter in the method signature, restrictedAnnotation. The part I am not sure about is how it gets the annotation type, it seems to be based on the parameter. And once you have the annotation you can get the values.
Why don't you just use Spring Security ? It's a brief to implement and use, I don't really see the point in wasting time reinventing the wheel.
Whith Spring AOP if you have a situation like MyManagerImpl implements MyManager the pointcut is applied to the interface method so MethodSignature describes the method defined on MyManager that doesn't have any annotation. the only way I've found to fix this is to inspect the class of the jp.getTarget() object and retrieve the corresponding method.