Skip to main content

How to create Annotation in Spring boot

 To create Custom Annotation in JAVA, @interface keyword is used.

The annotation contains : 


1. Retention : @Retention(RetentionPolicy.RUNTIME)

It specifies that annotation should be available at runtime.

2. Target : @Target({ElementType.METHOD})

It specifies that the annotation can only be applied to method. The target cane be modified to:

 @Target({ElementType.TYPE}) for class level annotation

@Target({ElementType.FIELD}) for field level annotation

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CustomAnnotation {
String value() default "default value";
}

value attribute is defined with @CustomAnnotation annotation. If you want to use the
 attribute in annotation. 
A single attribute value.

Example : 
public class Books {
    
    
@CustomAnnotation(value = "myBook")
    public void updateBookDetail() {
        // update book category name by annotation value
    }
}

HOW THIS CAN BE USED

1. Using Spring AOP :

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CustomAnnotationProcess {

@Pointcut("@annotation(customAnnotation)")
public void customAnnotationPointcut(final CustomAnnotation customAnnotation) {

}


@AfterReturning(pointcut = "customAnnotationPointcut(customAnnotation)",
returning = "transactionResponse")
public void updateBookCategory(final CustomAnnotation customAnnotation,
final Object transactionResponse) {
final String bookCategory = customAnnotation.value();
// Update book details
}
}

A). Aspect-Oriented Programming (AOP) with Spring and AspectJ annotations. Here's a 
breakdown of the key annotations and their purpose:

B). @Aspect: Indicates that the class is an aspect, which is a module that 
encapsulates behaviors affecting multiple classes.

C). @Pointcut: Declares a pointcut, which is a predicate that matches join points 
(points in the execution of the program, such as method calls) where advice 
(additional behavior) should be applied. In this case, the pointcut matches methods annotated with @CustomAnnotation.

D). @AfterReturning: Declares advice to be executed after a join point completes 
normally and returns a value. The pointcut attribute specifies the pointcut expression 
that defines where the advice should be applied, and the returning attribute specifies 
the name of the parameter in the advice method that will receive the return value of 
the join point.

E). @Component: Indicates that the class is a Spring component and should be 
automatically detected and registered as a bean in the Spring application context.

In this example, 
the CustomAnnotationProcess class serves as an aspect that processes methods annotated 
with @CustomAnnotation. The customAnnotationPointcut method defines a pointcut that 
matches such annotated methods. The updateBookCategory method is the advice that will
 be executed after the annotated methods return, and it receives the CustomAnnotation
 and the return value of the annotated method as parameters.


2. Process the Annotation

If your annotation requires special processing, you can use reflection to access and process the annotation at runtime


public class AnnotationProcessor {
public void processAnnotations(Object obj) {
Class<?> clazz = obj.getClass();
MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);
if (annotation != null) {
String value = annotation.value();
System.out.println("Annotation value: " + value);
}
}
}






Comments

Popular posts from this blog

Kafka And Zookeeper SetUp

 Kafka And Zookeeper SetUp zookeeper download Link : https://www.apache.org/dyn/closer.lua/zookeeper/zookeeper-3.8.3/apache-zookeeper-3.8.3-bin.tar.gz Configuration: zoo.conf # The number of milliseconds of each tick tickTime =2000 # The number of ticks that the initial # synchronization phase can take initLimit =10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit =5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir =/tmp/zookeeper # the port at which the clients will connect clientPort =2181 4 char whitelist in command arguments 4lw.commands.whitelist =* Start ZooKeeper Server $ bin/zkServer.sh start Check zookeeper status dheeraj.kumar@Dheeraj-Kumar bin % echo stat | nc localhost 2181 stat is 4 character whitelisted argument  Check Kafka running status : echo dump | nc localhost 2181 | grep broker Responsibility of Leader in Zookeeper: 1. Distrib...

Cache Policy

Cache policies determine how data is stored and retrieved from a cache, which is a small and fast storage area that holds frequently accessed data to reduce the latency of accessing that data from a slower, larger, and more distant storage location, such as main memory or disk. Different cache policies are designed to optimize various aspects of cache performance, including hit rate, latency, and consistency. Here are some common types of cache policies: Least Recently Used (LRU): LRU is a commonly used cache replacement policy. It evicts the least recently accessed item when the cache is full. LRU keeps track of the order in which items were accessed and removes the item that has not been accessed for the longest time. First-In-First-Out (FIFO): FIFO is a simple cache replacement policy. It removes the oldest item from the cache when new data needs to be stored, regardless of how frequently the items have been accessed. Most Recently Used (MRU): MRU removes the most recently accessed ...