Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Java

Annotations

What is an annotation, and who does what when you add one?

Why it exists — Before annotations, information such as "this method is a test" or "Spring creates objects of this class" had to be given through a rule, such as a method name that starts with test, or through an XML configuration file kept apart from the code, so when you changed the code you also had to update the configuration file separately. An annotation lets you write such a mark with @ right above the code it belongs to, so the code and the mark are seen in one place and are changed together.

Where it's used today — @Override makes the compiler check that you rewrote the parent's method correctly. Spring's @Service, @Repository, @Controller, and @Component make Spring create an object of that class and register it as a bean, and Spring reads @GetMapping and @Transactional too and acts on them. JUnit's @Test makes JUnit run that method as a test. You rarely make annotations yourself, and usually you attach the ones that Java and frameworks have already made.

An annotation is a tag that starts with @, such as @Service, @Override, or @Test, and that you put above a class or a method. The tag itself contains no code that runs, and what it means is decided by whatever reads it. @Override is read by the compiler, @Service by Spring (it creates objects of the classes it finds by component scanning and registers them as beans), and @Test by JUnit. In this lab you add and remove the three annotations, go through or skip the reader (Spring, JUnit), compile and run the same code, and see what changes. Then you look at the real declarations of @Service and @Override to see how far @Retention keeps a tag, and finally you make an annotation and the code that reads it yourself. OrderService, Order, OrderTest, and Job in the code are classes made as examples for this lab.

Checked against real execution · On the PC used to write this lab, 17 combinations of the code on the screen were compiled and run with JDK 21, Spring 7.0.9, and JUnit 6.0.3 (real component scanning, the JUnit Launcher, javap), and the result table, the exception and compile-time error messages, the bean name, and the real declarations of @Service, @Override, and @Test were checked against them

Concepts in this lab

Annotation
This is metadata that you attach to code. It does nothing by itself; the compiler or a framework reads it and acts on it. Some, like @Override, are used by the compiler for checks, and others, like @Transactional and @Autowired, are read by a framework at run time through reflection to apply a feature.
@Override
Why it exists — Overriding happens quietly as long as the name and parameters match, so if the name of the parent's method is changed later, the child's method stays as a separate method that is not an override, with no error at all. @Override writes the intention to override in the code, so that such a mismatch shows up as a compile-time error.
Where it's used today — You put it when you override toString, equals, or hashCode, or when you implement a method of an interface. When an IDE generates overriding code for you, it writes it too.
This is an annotation that shows that the method right below it overrides a method of a superclass or an interface. The compiler reads this tag and checks that it really overrides, and if not, it reports a compile-time error. It catches the mistake of misspelling the method name or its parameters and so creating a new method that does not override. It overrides even without it, and the behavior of the program does not change either, but to prevent mistakes you always put it on a method that overrides. It is an annotation that is kept only up to the source code, so it is not written to the class file.
@Service and @Repository
Why it exists — If every bean had only @Component, the code would not show what role a class has, and there would be no basis for treating roles differently, such as applying exception translation only to data access classes. So Spring made separate annotations that name the role, based on @Component.
Where it's used today — In a Spring web application, you put @Service on a service class that handles business rules and @Repository on a class that works with the database. An interface that extends Spring Data JPA's JpaRepository is found and registered by Spring separately, so it does not need @Repository.
@Service and @Repository are annotations that Spring provides. When you put one on a class, component scanning finds that class, creates an object of it, and registers it as a bean. Both have @Component on their declarations (a meta-annotation), so they are found in the same way as a class with @Component, and @Controller is the same. They have different names to show the role of the class (handling business logic, accessing data, handling requests). @Repository has one more effect: if a PersistenceExceptionTranslationPostProcessor is registered (Spring Boot registers it through auto-configuration when you use a data access module), the exceptions that a technology such as JPA throws from that bean are translated and thrown as Spring's DataAccessException hierarchy. The annotation itself is only a tag, so if you create an object with new without starting Spring, it does nothing.
Component scanning
Why it exists — If you register beans one by one with XML or @Bean methods for each class, the registration list must also be changed every time you create a class. Component scanning lets Spring find and register classes when you only put an annotation on them.
Where it's used today — Services, repositories, and controllers that you write yourself are usually registered this way. So you place the @SpringBootApplication class in the topmost package of the project, and to make scanning reach other packages, you specify them with the scanBasePackages attribute.
This feature finds the classes under a given package that carry @Component or one of its related annotations (such as @Service, @Repository, and @Controller) and registers them as beans automatically. In Spring Boot, the default target is the package of the class annotated with @SpringBootApplication and its subpackages.
@Test
Why it exists — Up to JUnit 3, a method whose name started with test was treated as a test, so method names had to be made to fit that rule. @Test makes tests be found by the attached marker regardless of the name, so you can name the method after what it checks.
Where it's used today — You put it above each method that is to be run as a test, and an IDE such as IntelliJ shows a run button next to a method with @Test. To run the same test several times with only the values changed, you attach @ParameterizedTest.
@Test is an annotation that you put above a method to tell JUnit that the method is a test method. According to the documentation, a method with @Test must not be private or static, and must not return a value. JUnit counts a method that has @Test (or an annotation such as @RepeatedTest or @ParameterizedTest) as a test, so a method without the marker is not counted as a test even if its content looks like a test. In the JUnit 6.0.3 that was run, when a class that has a method without @Test was run, the number of tests found was 0, and the method was never run, with no error and no failure.
@Retention and @Target
Why it exists — If there were no way to decide where each annotation can be put and how far it is kept, the compiler could not catch a tag meant for methods being put on a field by mistake, and a tag that only the compiler looks at would remain until run time. @Target and @Retention make whoever creates the annotation decide these two in the declaration.
Where it's used today — The side that uses an annotation usually does not write them. They are already written in the declarations of the annotations that Spring, JUnit, and Java provide, so whether it is read at run time (RUNTIME) and where it can be put are already decided. You write them together only when you make an annotation yourself.
These are two annotations that you put on the declaration of an annotation to set the properties of that annotation. @Retention decides how far the tag is kept. SOURCE keeps it only up to the source code (@Override), CLASS keeps it up to the class file (Spring's @Contract), and RUNTIME keeps it until run time so that it can be read with reflection (@Transactional, @Test, @Deprecated). If you do not write it, it is CLASS. @Target decides where it can be put (TYPE is a type declaration such as a class, METHOD is a method, FIELD is a field, and so on), and putting it somewhere that does not match is a compile-time error. The declaration of @Transactional has @Target({ElementType.TYPE, ElementType.METHOD}) and @Retention(RetentionPolicy.RUNTIME).
Meta-annotation
Why it exists — If you wrote separate code for each annotation to handle properties such as "where it can be put", "how far it is kept", and "whether Spring treats it as a bean", the reader would have to be changed every time a new annotation appears. A meta-annotation lets you write those properties as tags on the declaration, so that the reader can handle it by looking only at the declaration.
Where it's used today — Spring's @Service, @Repository, @Controller, @RestController, and @SpringBootApplication are all made by combining other annotations as meta-annotations. If you often put several annotations together, you can also declare an annotation yourself that has them as meta-annotations, to cut them down to one line.
A meta-annotation is an annotation that is put on the declaration of another annotation. The typical ones are @Target, @Retention, and @Documented, which Java provides, and the @Component on the declaration of Spring's @Service is also a meta-annotation. Spring follows and reads the annotations on a class down to the declarations of those annotations, so it finds a class with @Service through component scanning just like a class with @Component. The reflection method isAnnotationPresent does not follow them this way, so asking isAnnotationPresent(Component.class) about a class with @Service returns false.
@interface
Why it exists — If you could use only the annotations that Java has made in advance, you could not attach the tags that a framework or your own program needs. @interface lets anyone declare the tag they need, so that tools such as Spring and JUnit can create their own tags.
Where it's used today — Usually you do not write a declaration yourself; you attach the ones that Java, Spring, and JUnit have declared. You read a declaration when you look for the basis of a behavior, such as why @Service makes a bean. You declare one yourself when you attach the same tag in many places, such as "methods whose run time is to be measured", and use it together with a reader such as Spring AOP.
@interface is the syntax that declares an annotation. You write it by putting @ before the interface of an ordinary interface declaration. Java's @Override, Spring's @Service, and JUnit's @Test are all declared this way, and the @Target (where it can be put) and @Retention (how far it is kept) above the declaration decide the properties of that annotation. If the inside of the braces is empty, it is a tag that takes no values (a marker annotation), and if you put in declarations shaped like methods, they become elements that take values, as in @Service("name"). The declaration alone does not create any code that runs, and something else has to read the tag and act on it (the compiler, Spring, JUnit, or code we write). If you do not write @Retention when you declare one yourself, it is CLASS, and it cannot be read through reflection while the program runs.

Try these

Running with the default settings

  1. OrderService is a class made as an example for this lab, and the @Service above it is an annotation provided by Spring. An annotation is a tag that starts with @ and that you put above a class or a method. Writing @Service does not by itself create an object or run a method.
  2. javac compiles the two files. The compiler only checks that @Service is an annotation that can be put on a class, and records it in the class file. Spring declared @Service with @Retention(RetentionPolicy.RUNTIME), so it stays as a tag that can be read while the program runs.
  3. new AnnotationConfigApplicationContext("app") in main starts Spring. Spring scans the classes in the app package and reads their tags. This is called component scanning. What Spring looks for is @Component, and annotations such as @Service whose declaration has @Component on it.
  4. OrderService has @Service. Spring creates one OrderService object and registers it as a bean (an object that Spring creates and manages). The bean's name is orderService, the class name with the first letter changed to lowercase. What created the object is Spring, not a new in our code.
  5. context.getBean(OrderService.class) asks Spring for the OrderService bean. Spring returns the object it made, and "Order service", which service.name() returned, is printed.

Result of this run

Code

// File: app/OrderService.java
package app;

import org.springframework.stereotype.Service;

// OrderService is an example class we made; @Service is an annotation provided by Spring
@Service
public class OrderService {
    public String name() {
        return "Order service";
    }
}

// File: app/Main.java
package app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        // Start Spring. It scans the classes in the app package (component scanning)
        ApplicationContext context =
                new AnnotationConfigApplicationContext("app");
        // Ask for the OrderService object that Spring made
        OrderService service = context.getBean(OrderService.class);
        System.out.println(service.name());
    }
}

Assumptions of this model

The compiler and runtime are JDK 21.0.12.1, Spring Framework 7.0.9 (started with AnnotationConfigApplicationContext, without Spring Boot), and JUnit Jupiter 6.0.3 (run with JUnit Platform Launcher 6.0.3). For the seventeen combinations used in the questions (four for each of @Service, @Override, @Test, and our own @Run, plus one question that looks at the declarations), the code shown on the screen was taken as is from the code function of this lab and compiled with javax.tools. Those that compiled were run in a new Java process (the combinations that run @Test with JUnit were run with the Launcher), and the standard output, the exceptions, and the number of tests JUnit found and the number that passed were captured and checked against the result table. Component scanning is a real scan, and OrderService was not registered by hand. I also checked by running that the message of the NoSuchBeanDefinitionException, the compile-time error message for @Override, the bean name orderService, getBean still succeeding when @Repository, @Controller, or @Component is put in place of @Service, the compile-time error when @Service is put above a method, only Service remaining in RuntimeVisibleAnnotations in OrderService.class seen with javap -v while Override is absent, and Override not remaining in Order.class with @Override either. The declarations of @Service and @Override copied into the comments, and the declaration of @Test in a step sentence (@Retention(RUNTIME)), were checked against the meta-annotations and element names read with reflection while running, and the explanatory comments were not included. The hexadecimal number after Order@ that Object's toString() returns can differ on each run, so only its form was checked. The sentence that without @Retention it is CLASS and cannot be read while the program runs was not run again this time, and it relies on Section 9.6.4.2 of the Java Language Specification (Java SE 21) and on this lab's earlier run record (when a custom annotation has no @Retention, isAnnotationPresent is false). For the documentation, I checked Section 9.6 (@interface declarations), Section 9.6.4.1 (@Target), Section 9.6.4.2 (@Retention), and Section 9.6.4.4 (@Override) of the Java Language Specification, the sections on component scanning and meta-annotations in the Spring Framework reference, and the description of @Test in the JUnit User Guide. The sentence that the ./gradlew test command or the IDE's run button calls JUnit was not run in this lab. How Spring reads tags internally during component scanning, and how to use an annotation you made yourself together with Spring AOP, are not covered, and the detailed behavior of annotations is covered in the in-depth lab "Annotations".

Previous lab: Streams · Next lab: Threads

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these