The Full Stack Developer

define custom annotation spring

How to create a custom annotation in Spring Boot?

define custom annotation spring

Annotation is a powerful feature in Java.

You can plug in some logic by just adding a word !

Consider this annotation in Spring Data:


Add this to a method where you are performing a sequence of database operations and they suddenly turn transactional. If any of the database operation fails all the other executed database operations are rolled back automatically!

You can make use of the same power.

It’s quite easy to create an annotation in spring boot and plugin logic as and where you need it.

Here are the steps to follow:

STEP1: Create an interface with the annotation name

Let’s say we want to trace the requests and responses to a REST method in Spring Boot.

To do this let’s make use of a custom annotation.

Let’s call this

Now , in whichever method you add the above annotation , the method suddenly transforms into a traceable one. The requests and responses are traced automatically!

Let’s say we want to trace the below REST method “test”:

We want to print the input , the output and the ip address (which we can get from http servlet request object passed as the second parameter in the above method)

First let’s create the annotation.

Make use of @interface in Java to create the annotation like below:

Our annotation @Traceable is defined now.

@Target in the above annotation definition defines where to apply the annotation . In our case it is at the method level , so we give ElementType.METHOD as parameter

@Retention denotes when to apply this annotation , in our case it is at run time

Having defined the annotation now let’s build the logic to be applied .

To do this , move to step 2

STEP2: Create an Aspect

The kind of programming we implement using annotations is called Aspect Oriented Programming or declarative programming. You declare in code what to do at certain areas (point cuts is the technical term for this)

To make use of the above annotation , build the logic inside an Aspect class:

Use the annotation @Aspect to let know Spring that this is an Aspect class.

Use the annotation @Component so that Spring will consider this class as a Spring bean.

Create a method with any name and apply the annotation @Around() to define the logic you want to execute .

@Before and @After are other annotations which can be used , they represent the logic to be executed before the start of a method and after the end of a method respectively.

In our case we want to trace both the request and the response , so let’s use @Around

Inside the @Around annotation , pass the annotation name which you created so that Spring knows that it needs to apply the logic around this annotation.

The method should accept a single parameter ProceedingJoinPoint and should return Object data type.

The ProceedingJoinPoint gives access to the method .

From this object you can retrieve the parameters using getArgs() method which returns the input parameters in an array

You can get the input from the first parameter and the ip address from the second parameter as shown above.

You can get the response by calling joinPoint.proceed() . This is where the original method is executed.

Having built the logic , now lets plugin the annotation where we want

STEP3: Add the annotation

Add the annotation on the REST method as below:

We are all set.

Now when you hit the above REST method , the below gets printed:

define custom annotation spring

All because of the @Traceable annotation!

You can add this annotation to whichever REST method you want to trace and the tracing will take place automatically.

Note : you need to use spring-boot-starter-web and spring-boot-starter-aop dependencies for the above to work.

Here is the github link:

Share this:

Leave a reply cancel reply.

Custom annotations with Spring

Bassem 06/06

define custom annotation spring

In this post we are going to see the difference between @Repository , @Service , @Configuration , and @Controller annotations and how to make a custom one, so that our classes are initiated in the Spring IoC ( Inversion of Control ) container as any class annotated with a such annotation. By creating custom annotations for dependency injection, we can isolate our service layer (application core) from the framework used. If we want to migrate our application to another framework we just need to edit those annotations without touching our logic layer. First of all, the above-mentioned annotation and the @Component one are common Spring bean annotations and used as stereotype for any Spring-managed component. The classes annotated will be autodetected through classpath scanning.

What is the difference ?

Actually, there is no major difference between @Repository , @Service , @Configuration , and @Controller , all of them are annotated with @Component . You can see the code of @Service annotation in the following snippet:

They are used to differentiate the layers:

@Service , for business logic classes;

@Controller , for representation layer;

@Configuration , for any configuration ;

@Repository , for data base access classes. One exception here, that Spring boot provide automatically a PersistenceExceptionTranslationPostProcessor (which is needed), making the class eligible for Spring DataAccessException translation.

What are we going to build?

We will build a custom service annotation called @OurCustomService , which will be used to annotate our service layer classes and make them eligible for IoC Spring container.

Code example

First of all, in our pom.xml we just need the spring boot starter dependency:

Then we create our custom annotation:

It's a copy of the @Service Spring annotation. Kindly note that the interface it self is annotated with @Component .

Then we create our service layer by creating an interface and its implementation. This last one is annotated with @OurCustomService :

Finally, we test our code in the main class, by searching the ApplicationContext for our bean DemoServiceImpl :

When we run the application, we can find the invocation in the logs:

That's it; all the code written in this post can be found on GitHub .

Feel free to join the conversation on Twitter 👇

The difference between Repository, Service, Configuration, and Controller annotations and how to make a custom one in #springboot and #Java — soloCoding (@s0l0c0ding) June 8, 2022


mscharhag, Programming and Stuff; // Blog of Michael Scharhag

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Sunday, 23 February, 2020

  • Composing custom annotations with Spring

Java Annotations were introduced with Java 5 back in 2004 as a way to add meta data into Java source code. Today many major frameworks like Spring (including Spring Boot) or Hibernate heavily rely on annotations.

In this post we will have a look at a very useful Spring feature which allows us to create our own annotations based on one or more Spring annotations.

Composing a custom annotation

Assume we have a set of Spring annotations we often use together. A common example is the combination of @Service and @Transactional :

Instead of repeating both annotations over and over again, we can create our own annotation containing these two Spring annotations. Creating our own annotation is very easy and looks like this:

An annotation is defined with the @interface keyword (instead of class or interface). The standard Java Annotation @Retention is used to indicate that the annotation should be processable at runtime. We also added both Spring annotations to our annotation.

Now we can use our own @MyService annotations to annotate our services:

Spring now detects that @MyService is annotated with @Service and @Transactional and provides the same behaviour as the previous example with both annotations present at the UserService class.

Note that this is a feature of Spring's way of annotation processing and not a general Java feature. Annotations of other frameworks and libraries might not work if you add them to your own annotation.

Example use cases

Custom annotations can be used in various situations to improve the readability of our code. Here are two other examples that might come in handy.

Maybe we need a property value in various locations of our code. Properties are often injected using Spring's @Value annotation:

In such a situation we can move the property expression out of our code into a separate annotation:

Within our code we can now use @ApiKey instead of repeating the property expression everywhere:

Another example are integration tests. Within tests often various Spring annotations are used to define the test setup. These annotations can be grouped together using a custom annotation. For example, we can create a @MockMvcTest annotations that defines the Spring setup for mock mvc tests:

The definition of our tests look a lot cleaner now. We just have to add @MockMvcTest to get the complete test setup:

Note that our @MockMvcTest annotation also contains the @ExtendWith annotation of JUnit 5. Like Spring, JUnit 5 is also able to detect this annotation if it is added to your own custom annotation. Be aware that this will not work if you are still using JUnit 4. With JUnit 4 you have to use @RunWith instead of @ExtendWith . Unfortunatelly @RunWith only works when placed directly at the test class.

Examples in Spring

Spring uses this feature in various situations to define shortcuts for common annotations.

Here are a few examples:

  • @GetMapping is the short version for @RequestMapping(method = {RequestMethod.GET}) .
  • @RestController is a composition of @Controller and @ResponseBody .
  • Spring Boots @SpringBootApplication is a shortcut for @SpringBootConfiguration , @EnableAutoConfiguration and @ComponentScan

You can verify this yourself by looking into the definition of these annotations in Spring's source code.

Tags: Java , Spring

--> --> --> , --> -->