Dev Learning Lab

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

Learn › Java › Generics, enums, and annotations

Annotations

What really happens when you just add an @?

Why it exists — Before annotations, information such as "wrap this method in a transaction" or "this method is a test" was written in a place apart from the code, such as an XML configuration file, or was expressed by a rule such as a method name that starts with test. When you changed the code, it was hard to change the separate configuration along with it. An annotation writes that information right above the class or method it concerns, and lets the compiler or a framework read it.

Where it's used today — Spring's @Transactional, @Component, and @GetMapping, JPA's @Entity, and JUnit's @Test are read by the framework with reflection while the program runs. Java's @Override, @FunctionalInterface, and @Deprecated are read by the compiler, which reports an error or a warning. The declaration of such an annotation carries @Retention and @Target, which decide how far the tag is kept and where it can be put.

An annotation (a tag that starts with @, such as @Transactional, @Test, or @Override) is a tag that you put on code. The tag itself does nothing. It takes on meaning only when something reads it, and there are two main kinds of readers: the compiler (@Override, @FunctionalInterface, @Deprecated), and frameworks that read it with reflection while the program runs (Spring's @Transactional, JUnit's @Test). The @Retention on the declaration of each annotation decides how far the tag is kept: only in the source code (SOURCE), up to the class file (CLASS), or until run time (RUNTIME). That also decides who can read it.

Checked against real execution · On the PC used to write this lab, 24 combinations were compiled and run with the code on the screen on JDK 21, Spring 7.0.9 (H2), and JUnit 6.0.3, and the result table, the compiler messages, the slot of the class file where the annotation was written, whether the object is a proxy and the number of transactions started and committed, and the number of tests JUnit found were checked

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.
Reflection
Why it exists — A framework cannot know in advance the names of the classes users will write later, so ordinary code cannot create objects of those classes or call their methods. Reflection makes this possible by inspecting classes while the program runs and letting you work with them by name alone.
Where it's used today — You rarely use it directly in application code; it is used when building frameworks, testing tools, and serialization libraries. If the same job can be done with interfaces and polymorphism, that way is safer because it gets compile-time type checking.
This feature lets a running program inspect information about a class (its fields, methods, constructors, and annotations) and create objects or call methods by name. Spring's dependency injection, JPA's entity handling, and JSON serialization libraries all work on top of it. It is slower than a normal call and does not get compile-time type checking.
@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).
@Transactional
This annotation is placed on a method or a class so that its scope runs as one transaction. The proxy starts a transaction before the method runs, commits if the method ends normally, and rolls back according to the rules if an exception occurs. You do not have to write the code that starts and ends the transaction yourself, so this is called a declarative transaction.
Proxy
This is a stand-in object that receives calls in place of the real object. When it receives a call, it does some additional work and then passes the call on to the real object. Spring wraps a bean that needs a feature such as AOP or @Transactional in such an object and registers it in the container, so what other beans receive by injection is this stand-in, not the real object.
@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.
@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.
@Deprecated
Why it exists — If a library removes an old API right away, the code that was using it breaks all at once. Before removing it, @Deprecated sends the signal "this will disappear soon, so switch to something else" in advance as a compile warning, to give time to move over.
Where it's used today — It is on old APIs of Java and Spring (the constructor of Integer, old configuration methods, and so on), and you see it as a compile warning or as a strikethrough in a development tool. A library author uses it to announce an API that will change.
This is an annotation provided by Java that marks something that you should no longer use. You put it on classes, methods, constructors, fields, and so on. since tells from when, and forRemoval tells whether it is planned to be removed. The compiler gives a warning when our code uses an API that has it. Because it has to be read from the class file of a library, its declaration has @Retention(RetentionPolicy.RUNTIME). For example, the constructor Integer(int) of Integer has @Deprecated(since = "9", forRemoval = true), so compiling new Integer(5) gives the warning "[removal] … has been deprecated and marked for removal". It is only a warning, so the behavior does not change.
@FunctionalInterface
Why it exists — If someone adds one more abstract method to a functional interface, errors are scattered at every place that used the interface as a lambda, and it is hard to find the cause. @FunctionalInterface writes the meaning "for lambdas" in the declaration, so that such a change is blocked right at the place of the declaration.
Where it's used today — You put it on an interface that you made to be used as a lambda. It is on all the interfaces in the java.util.function package of the Java standard library.
This is an annotation provided by Java that says this interface is a functional interface to be used as a lambda, that is, that it has exactly one abstract method. The compiler reads it, and if the number of abstract methods is not one, it reports the error "Unexpected @FunctionalInterface annotation" at the place where the interface is declared. Even without it, an interface with one abstract method can be used as a lambda, so it does not change the behavior. It is on Java's Runnable, Comparator, Function, and others.

Try these

Running with the default settings

  1. AppConfig and OrderService are classes made as examples. We added @Transactional, which Spring provides, above order(). The real declaration of @Transactional (spring-tx 7.0.9) has @Target({ElementType.TYPE, ElementType.METHOD}) and @Retention(RetentionPolicy.RUNTIME). That means it can be put on classes and methods, and the tag is kept until run time.
  2. javac compiles it: the compiler only checks that @Transactional is an annotation that may be put on a method (@Target) and passes it. It does nothing about transactions. It is RUNTIME, so the tag is written to RuntimeVisibleAnnotations (the slot that is visible at run time too) of OrderService.class.
  3. new AnnotationConfigApplicationContext(AppConfig.class): the Spring container reads the configuration class AppConfig. @EnableTransactionManagement is present, so the parts that find @Transactional and apply transactions are registered as beans. They are the auto-proxy creator (InfrastructureAdvisorAutoProxyCreator), which checks whether a proxy is needed when a bean is created, and the transaction advisor, which reads @Transactional.
  4. When it creates the orderService bean, Spring uses reflection to look at the annotations on the methods of OrderService. It finds @Transactional on order(), so it registers an object of a proxy class made by extending OrderService (OrderService$SpringCGLIB$0) as the bean. The proxy holds a reference to the original OrderService object, and when it receives a method call, it does the transaction work before and after and calls the method of the original object.
  5. order.isAnnotationPresent(Transactional.class) runs: this asks directly, with reflection, whether @Transactional is on order(). The result is true. It is RUNTIME, so the tag remains until run time. The check Spring made while creating the bean is based on the same reflection information (getDeclaredAnnotations).
  6. ctx.getBean(OrderService.class): you get the bean from Spring. The class of the object you got is OrderService$SpringCGLIB$0, that is, a proxy that Spring made.
  7. service.order() runs: service is a proxy. The proxy first starts a transaction with the transaction manager (DataSourceTransactionManager) and then calls order() of the original OrderService object. Inside it, isActualTransactionActive() is true. When order() ends, the proxy commits.

Result of this run

Code

// AppConfig and OrderService are classes made as examples
// The annotations and classes such as DriverManagerDataSource are provided by Spring
@Configuration
@EnableTransactionManagement
class AppConfig {
    @Bean
    DataSource dataSource() {
        return new DriverManagerDataSource("jdbc:h2:mem:annot");
    }

    @Bean
    PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    OrderService orderService() {
        return new OrderService();
    }
}

class OrderService {
    @Transactional
    public void order() {
        boolean inTx = TransactionSynchronizationManager.isActualTransactionActive();
        System.out.println("order ran, in a transaction: " + inTx);
    }
}

// From here on, the code is inside main (the Main class, the main declaration, and imports are omitted)
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
    Method order = OrderService.class.getMethod("order");
    System.out.println("Is @Transactional visible: " + order.isAnnotationPresent(Transactional.class));
    OrderService service = ctx.getBean(OrderService.class);
    System.out.println("Class of service: " + service.getClass().getSimpleName());
    service.order();
}

Assumptions of this model

Twenty-four combinations (@Transactional 8, @Test 2, retention policies 2, @Override 4, @Deprecated 2, @FunctionalInterface 4, and our own @Timed 2) were compiled and run on JDK 21 with the code on the screen as it is, and checked. For @Transactional, a real container was started with Spring 7.0.9 and an H2 in-memory database, and I also checked whether the object you get is a proxy, whether @EnableTransactionManagement registers the auto-proxy creator, and how many transactions were started and committed by one call to order() (counted with a listener attached to the transaction manager). @Test was run with the Launcher of JUnit 6.0.3, and the number of tests found and the number that passed were checked. The compiler messages were received in English, and in which slot of the class file (RuntimeVisibleAnnotations or RuntimeInvisibleAnnotations) an annotation was written was checked with javap -v. The @Retention and @Target of the standard annotations mentioned in the text, and the @Deprecated value on Integer(int), were read with reflection from libraries of the same versions and checked. The code on the screen omits the import statements and the Main class and main declaration (the @Test code shows the imports too). That Spring finds annotations based on getDeclaredAnnotations of Java reflection, that Spring's @Contract is made for static analysis tools to read, and that Spring Boot's auto-configuration takes the place of @EnableTransactionManagement are explanations written after reading the Spring documentation and source, and they were not checked by running. Tools that read annotations at compile time and generate code (annotation processors) are not covered.

Previous lab: Enum classes · Next lab: ArrayList and LinkedList

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these