HowToDoInJava

Spring Annotations List

Lokesh Gupta

June 25, 2023

Learn about the most widely used spring annotations . In this tutorial, we will briefly cover the important annotations which are provided by spring core to define beans and create complex application context configurations.

1. Annotations in Spring Framework

Similar to other places, annotations help by providing metadata and instructions to the Spring container. They allow the container to understand and configure various components within a Spring application.

To make it more precise, annotations help during component scanning, dependency injection, autowiring, defining configurations, aspect-oriented programming, data access, testing and many more areas. Over all annotations provide a declarative way to express the intentions and behavior of components, leading to cleaner, more maintainable code.

2. Bean Annotations

In the Spring Framework, a bean is an object that is instantiated, assembled, and managed by the Spring IoC (Inversion of Control) container . The container also performs dependency injection , allowing beans to be wired together and collaborate with each other.

The following annotations provide metadata to Spring to control how to instantiate, configure, and wire the beans together.

The @Bean is a method-level annotation used to declare a spring bean. When the container executes the annotated method, it registers the return value as a bean within a  BeanFactory .

By default, the bean name will be the same as the method name. To customize the bean name, use its’ name ‘  or  ‘ value ‘ attribute.

2.2. @Component , @Controller , @Repository , @Service

These annotations are called stereotype annotations . When component scanning is enabled, Spring will automatically import these beans into the container and inject them into dependencies.

  • The  @Component  annotation is a generic annotation and marks a Java class as a bean.
  • The @Controller  annotation marks a class as a Spring MVC controller.
  • The  @Repository  annotation is a specialization of the  @Component  annotation. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring  DataAccessException .
  • The  @Service  annotation is also a specialization of @Component and used over service-layer classes because it specifies intent better. It doesn’t currently provide any additional behavior.

2.3. @Qualifier

During autowiring, if more than one bean of the same type is available in the container then the container will throw runtime exception. To fix this problem, we have to specifically tell Spring which bean has to be injected using this annotation.

In the given example, if there are two beans of type  Repository  then on runtime, the bean with the name ‘ fsRepository ‘ will be injected.

2.4. @Autowired

This annotation marks a constructor, field, setter method, or config method as to be autowired by dependency injection. We can mark whether the annotated dependency is required (mandatory to populate) or not using it’s ‘required’ attribute. By default, its value is ‘true’.

2.5. @Value

Applicable at the field or method/constructor parameter level, and indicates a default value expression for the affected argument.

Indicates whether a bean is to be lazily initialized. By default, in spring DI, eager initialization will occur. When applied over any bean, initialization of that bean will not happen until referenced by another bean or explicitly retrieved from the enclosing  BeanFactory .

2.7. @DependsOn

During component scanning, it is used to specify the beans on which the current bean depends on. The specified beans are guaranteed to be created by the container before this bean.

2.8. @Lookup

Indicates a method as a lookup method . It is best used for injecting a prototype-scoped bean into a singleton bean .

2.9. @Primary

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. When not using  @Primary , we may need to provide  @Qualifier  annotation to correctly inject the beans.

In the given example, when  FooRepository  will be autowired, the instance of  HibernateFooRepository  will be injected – until  @Qualifier  annotation is used.

2.10. @Scope

Indicates the name of a scope to use for instances of the annotated type. In Spring, beans can be in one of six bean scopes i.e. singleton, prototype, request, session, application and WebSocket. Note that the default scope is ‘ singleton ‘.

3. Configuration Annotations

The following discussed annotations help in binding the different beans together to form the runtime application context. They control how the other beans are discovered and the scope where they can be used.

3.1. @ComponentScan

@ComponentScan  along with  @Configuration  is used to enable and configure component scanning. By default, if we do not specify the path, it scans the current package and all of its sub-packages for components.

Using component scanning, spring can auto-scan all classes annotated with the stereotype annotations @Component , @Controller , @Service and @Repository  and configure them with  BeanFactory .

3.2. @Configuration

It indicates that a class declares one or more  @Bean  methods and can be processed by the container to generate bean definitions when used along with  @ComponentScan .

3.3. @Profile

It indicates that a component is eligible for bean registration when one or more specified profiles are active. A profile is a named logical grouping of beans e.g. dev, prod etc.

3.4. @Import and @ImportResource

The @Import annotation indicates one or more component classes to import – typically  @Configuration  classes. The @Bean definitions declared in imported  @Configuration  classes should be accessed by using  @Autowired  injection.

Similar to @Import , the @ImportResource indicates one or more resources containing bean definitions to import. It is used for XML bean definitions just like  @Import  is used for Java configuration using  @Bean .

3. Conclusion

The above-discussed annotations are not the complete list. You can explore more such annotations in the Spring framework documentation for the most updated information on these.

Drop me your questions related to the above-provided spring annotations list or their explanations.

Happy Learning !!

Further reading:

  • Spring Interview Questions with Answers
  • Docker Interview Questions for DevOps
  • Spring Boot Interview Questions for Experienced Developers
  • Spring Bean Scopes
  • Spring WebMVC Interview Questions
  • Spring Boot and Angular Application Example

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

Spring Framework Guru

Spring framework annotations.

Spring Framework Guru

The Java Programming language provided support for Annotations from Java 5.0. Leading Java frameworks were quick to adopt annotations and the Spring Framework started using annotations from the release 2.5. Due to the way they are defined, annotations provide a lot of context in their declaration.

Prior to annotations, the behavior of the Spring Framework was largely controlled through XML configuration. Today, the use of annotations provide us tremendous capabilities in how we configure the behaviors of the Spring Framework.

In this post, we’ll take a look at the annotations available in the Spring Framework.

Core Spring Framework Annotations

This annotation is applied on bean setter methods. Consider a scenario where you need to enforce a required property. The @Required annotation indicates that the affected bean must be populated at configuration time with the required property. Otherwise an exception of type BeanInitializationException is thrown.

This annotation is applied on fields, setter methods, and constructors. The @Autowired annotation injects object dependency implicitly.

When you use @Autowired on fields and pass the values for the fields using the property name, Spring will automatically assign the fields with the passed values.

You can even use @Autowired on private properties, as shown below. (This is a very poor practice though!)

When you use @Autowired on setter methods, Spring tries to perform the by Type autowiring on the method. You are instructing Spring that it should initiate this property using setter method where you can add your custom code, like initializing any other property with this property.

Consider a scenario where you need instance of class A , but you do not store A in the field of the class. You just use A to obtain instance of B , and you are storing B in this field. In this case setter method autowiring will better suite you. You will not have class level unused fields.

When you use @Autowired on a constructor, constructor injection happens at the time of object creation. It indicates the constructor to autowire when used as a bean. One thing to note here is that only one constructor of any bean class can carry the @Autowired annotation.

NOTE: As of Spring 4.3, @Autowired became optional on classes with a single constructor. In the above example, Spring would still inject an instance of the Person class if you omitted the @Autowired annotation.

This annotation is used along with @Autowired annotation. When you need more control of the dependency injection process, @Qualifier can be used. @Qualifier can be specified on individual constructor arguments or method parameters. This annotation is used to avoid confusion which occurs when you create more than one bean of the same type and want to wire only one of them with a property.

Consider an example where an interface BeanInterface is implemented by two beans BeanB1 and BeanB2 .

Now if BeanA autowires this interface, Spring will not know which one of the two implementations to inject. One solution to this problem is the use of the @Qualifier annotation.

With the @Qualifier annotation added, Spring will now know which bean to autowire where beanB2 is the name of BeanB2 .

  • @Configuration

This annotation is used on classes which define beans. @Configuration is an analog for XML configuration file – it is configuration using Java class. Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.

Here is an example:

  • @ComponentScan

This annotation is used with @Configuration annotation to allow Spring to know the packages to scan for annotated components. @ComponentScan is also used to specify base packages using basePackageClasses or basePackage attributes to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

Checkout this post for an in depth look at the Component Scan annotation.

This annotation is used at the method level. @Bean annotation works with @Configuration to create Spring beans. As mentioned earlier, @Configuration will have methods to instantiate and configure dependencies. Such methods will be annotated with @Bean . The method annotated with this annotation works as bean ID and it creates and returns the actual bean.

This annotation is used on component classes. By default all autowired dependencies are created and configured at startup. But if you want to initialize a bean lazily, you can use @Lazy annotation over the class. This means that the bean will be created and initialized only when it is first requested for. You can also use this annotation on @Configuration classes. This indicates that all @Bean methods within that @Configuration should be lazily initialized.

This annotation is used at the field, constructor parameter, and method parameter level. The @Value annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowired annotation tells Spring to inject object into another when it loads your application context, you can also use @Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and ${...} placeholders.

Spring Framework Stereotype Annotations

This annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.

@Controller

The @Controller annotation is used to indicate the class is a Spring controller. This annotation can be used to identify controllers for Spring MVC or Spring WebFlux.

This annotation is used on a class. The @Service marks a Java class that performs some service, such as execute business logic, perform calculations and call external APIs. This annotation is a specialized form of the @Component annotation intended to be used in the service layer.

@Repository

This annotation is used on Java classes which directly access the database. The @Repository annotation works as marker for any class that fulfills the role of repository or Data Access Object.

This annotation has a automatic translation feature. For example, when an exception occurs in the @Repository there is a handler for that exception and there is no need to add a try catch block.

Spring Boot Annotations

  • @EnableAutoConfiguration

This annotation is usually placed on the main application class. The @EnableAutoConfiguration annotation implicitly defines a base “search package”. This annotation tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

@SpringBootApplication

This annotation is used on the application class while setting up a Spring Boot project. The class that is annotated with the @SpringBootApplication must be kept in the base package. The one thing that the @SpringBootApplication does is a component scan. But it will scan only its sub-packages. As an example, if you put the class annotated with @SpringBootApplication in com.example then @SpringBootApplication will scan all its sub-packages, such as com.example.a , com.example.b , and com.example.a.x .

The @SpringBootApplication is a convenient annotation that adds all the following:

Spring MVC and REST Annotations

This annotation is used on Java classes that play the role of controller in your application. The @Controller annotation allows autodetection of component classes in the classpath and auto-registering bean definitions for them. To enable autodetection of such annotated controllers, you can add component scanning to your configuration. The Java class annotated with @Controller is capable of handling multiple request mappings.

This annotation can be used with Spring MVC and Spring WebFlux.

@RequestMapping

This annotation is used both at class and method level. The @RequestMapping annotation is used to map web requests onto specific handler classes and handler methods. When @RequestMapping is used on class level it creates a base URI for which the controller will be used. When this annotation is used on methods it will give you the URI on which the handler methods will be executed. From this you can infer that the class level request mapping will remain the same whereas each handler method will have their own request mapping.

Sometimes you may want to perform different operations based on the HTTP method used, even though the request URI may remain the same. In such situations, you can use the method attribute of @RequestMapping with an HTTP method value to narrow down the HTTP methods in order to invoke the methods of your class.

Here is a basic example on how a controller along with request mappings work:

In this example only GET requests to /welcome is handled by the welcomeAll() method.

This annotation also can be used with Spring MVC and Spring WebFlux.

The @RequestMapping annotation is very versatile. Please see my in depth post on Request Mapping bere .

@CookieValue

This annotation is used at method parameter level. @CookieValue is used as argument of request mapping method. The HTTP cookie is bound to the @CookieValue parameter for a given cookie name. This annotation is used in the method annotated with @RequestMapping . Let us consider that the following cookie value is received with a http request:

JSESSIONID=418AB76CD83EF94U85YD34W

To get the value of the cookie, use @CookieValue like this:

@CrossOrigin

This annotation is used both at class and method level to enable cross origin requests. In many cases the host that serves JavaScript will be different from the host that serves the data. In such a case Cross Origin Resource Sharing (CORS) enables cross-domain communication. To enable this communication you just need to add the @CrossOrigin annotation.

By default the @CrossOrigin annotation allows all origin, all headers, the HTTP methods specified in the @RequestMapping annotation and maxAge of 30 min. You can customize the behavior by specifying the corresponding attribute values.

An example to use @CrossOrigin at both controller and handler method levels is this.

In this example, both getExample() and getNote() methods will have a maxAge of 3600 seconds. Also, getExample() will only allow cross-origin requests from http://example.com , while getNote() will allow cross-origin requests from all hosts.

Composed @RequestMapping Variants

Spring framework 4.3 introduced the following method-level variants of @RequestMapping annotation to better express the semantics of the annotated methods. Using these annotations have become the standard ways of defining the endpoints. They act as wrapper to @RequestMapping.

These annotations can be used with Spring MVC and Spring WebFlux.

@GetMapping

This annotation is used for mapping HTTP GET requests onto specific handler methods. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

@PostMapping

This annotation is used for mapping HTTP POST requests onto specific handler methods. @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)

@PutMapping

This annotation is used for mapping HTTP PUT requests onto specific handler methods. @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)

@PatchMapping

This annotation is used for mapping HTTP PATCH requests onto specific handler methods. @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH)

@DeleteMapping

This annotation is used for mapping HTTP DELETE requests onto specific handler methods. @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE)

[divider style=”4″]

@ExceptionHandler

This annotation is used at method levels to handle exception at the controller level. The @ExceptionHandler annotation is used to define the class of exception it will catch. You can use this annotation on methods that should be invoked to handle an exception. The @ExceptionHandler values can be set to an array of Exception types. If an exception is thrown that matches one of the types in the list, then the method annotated with matching @ExceptionHandler will be invoked.

@InitBinder

This annotation is a method level annotation that plays the role of identifying the methods which initialize the WebDataBinder – a DataBinder that binds the request parameter to JavaBean objects. To customise request parameter data binding , you can use @InitBinder annotated methods within our controller. The methods annotated with @InitBinder all argument types that handler methods support. The @InitBinder annotated methods will get called for each HTTP request if you don’t specify the value element of this annotation. The value element can be a single or multiple form names or request parameters that the init binder method is applied to.

@Mappings and @Mapping

This annotation is used on fields. The @Mapping annotation is a meta annotation that indicates a web mapping annotation. When mapping different field names, you need to configure the source field to its target field and to do that you have to add the @Mappings annotation. This annotation accepts an array of @Mapping having the source and the target fields.

@MatrixVariable

This annotation is used to annotate request handler method arguments so that Spring can inject the relevant bits of matrix URI. Matrix variables can appear on any segment each separated by a semicolon. If a URL contains matrix variables, the request mapping pattern must represent them with a URI template. The @MatrixVariable annotation ensures that the request is matched with the correct matrix variables of the URI.

@PathVariable

This annotation is used to annotate request handler method arguments. The @RequestMapping annotation can be used to handle dynamic changes in the URI where certain URI value acts as a parameter. You can specify this parameter using a regular expression. The @PathVariable annotation can be used declare this parameter.

@RequestAttribute

This annotation is used to bind the request attribute to a handler method parameter. Spring retrieves the named attributes value to populate the parameter annotated with @RequestAttribute . While the @RequestParam annotation is used bind the parameter values from query string, the @RequestAttribute is used to access the objects which have been populated on the server side.

@RequestBody

This annotation is used to annotate request handler method arguments. The @RequestBody annotation indicates that a method parameter should be bound to the value of the HTTP request body. The HttpMessageConveter is responsible for converting from the HTTP request message to object.

@RequestHeader

This annotation is used to annotate request handler method arguments. The @RequestHeader annotation is used to map controller parameter to request header value. When Spring maps the request, @RequestHeader checks the header with the name specified within the annotation and binds its value to the handler method parameter. This annotation helps you to get the header details within the controller class.

@RequestParam

This annotation is used to annotate request handler method arguments. Sometimes you get the parameters in the request URL, mostly in GET requests. In that case, along with the @RequestMapping annotation you can use the @RequestParam annotation to retrieve the URL parameter and map it to the method argument. The @RequestParam annotation is used to bind request parameters to a method parameter in your controller.

@RequestPart

This annotation is used to annotate request handler method arguments. The @RequestPart annotation can be used instead of @RequestParam to get the content of a specific multipart and bind to the method argument annotated with @RequestPart . This annotation takes into consideration the “Content-Type” header in the multipart(request part).

@ResponseBody

This annotation is used to annotate request handler methods. The @ResponseBody annotation is similar to the @RequestBody annotation. The @ResponseBody annotation indicates that the result type should be written straight in the response body in whatever format you specify like JSON or XML. Spring converts the returned object into a response body by using the HttpMessageConveter .

@ResponseStatus

This annotation is used on methods and exception classes. @ResponseStatus marks a method or exception class with a status code and a reason that must be returned. When the handler method is invoked the status code is set to the HTTP response which overrides the status information provided by any other means. A controller class can also be annotated with @ResponseStatus which is then inherited by all @RequestMapping methods.

@ControllerAdvice

This annotation is applied at the class level. As explained earlier, for each controller you can use @ExceptionHandler on a method that will be called when a given exception occurs. But this handles only those exception that occur within the controller in which it is defined. To overcome this problem you can now use the @ControllerAdvice annotation. This annotation is used to define @ExceptionHandler , @InitBinder and @ModelAttribute methods that apply to all @RequestMapping methods. Thus if you define the @ExceptionHandler annotation on a method in @ControllerAdvice class, it will be applied to all the controllers.

@RestController

This annotation is used at the class level. The @RestController annotation marks the class as a controller where every method returns a domain object instead of a view. By annotating a class with this annotation you no longer need to add @ResponseBody to all the RequestMapping method. It means that you no more use view-resolvers or send html in response. You just send the domain object as HTTP response in the format that is understood by the consumers like JSON.

@RestController is a convenience annotation which combines @Controller and @ResponseBody .

@RestControllerAdvice

This annotation is applied on Java classes. @RestControllerAdvice is a convenience annotation which combines @ControllerAdvice and @ResponseBody . This annotation is used along with the @ExceptionHandler annotation to handle exceptions that occur within the controller.

@SessionAttribute

This annotation is used at method parameter level. The @SessionAttribute annotation is used to bind the method parameter to a session attribute. This annotation provides a convenient access to the existing or permanent session attributes.

@SessionAttributes

This annotation is applied at type level for a specific handler. The @SessionAtrributes annotation is used when you want to add a JavaBean object into a session. This is used when you want to keep the object in session for short lived. @SessionAttributes is used in conjunction with @ModelAttribute . Consider this example.

The @ModelAttribute name is assigned to the @SessionAttributes as value. The @SessionAttributes has two elements. The value element is the name of the session in the model and the types element is the type of session attributes in the model.

Spring Cloud Annotations

@enableconfigserver.

This annotation is used at the class level. When developing a project with a number of services, you need to have a centralized and straightforward manner to configure and retrieve the configurations about all the services that you are going to develop. One advantage of using a centralized config server is that you don’t need to carry the burden of remembering where each configuration is distributed across multiple and distributed components.

You can use Spring cloud’s @EnableConfigServer annotation to start a config server that the other applications can talk to.

@EnableEurekaServer

This annotation is applied to Java classes. One problem that you may encounter while decomposing your application into microservices is that, it becomes difficult for every service to know the address of every other service it depends on. There comes the discovery service which is responsible for tracking the locations of all other microservices. Netflix’s Eureka is an implementation of a discovery server and integration is provided by Spring Boot. Spring Boot has made it easy to design a Eureka Server by just annotating the entry class with @EnableEurekaServer .

@EnableDiscoveryClient

This annotation is applied to Java classes. In order to tell any application to register itself with Eureka you just need to add the @EnableDiscoveryClient annotation to the application entry point. The application that’s now registered with Eureka uses the Spring Cloud Discovery Client abstraction to interrogate the registry for its own host and port.

@EnableCircuitBreaker

This annotation is applied on Java classes that can act as the circuit breaker. The circuit breaker pattern can allow a micro service continue working when a related service fails, preventing the failure from cascading. This also gives the failed service a time to recover.

The class annotated with @EnableCircuitBreaker will monitor, open, and close the circuit breaker.

@HystrixCommand

This annotation is used at the method level. Netflix’s Hystrix library provides the implementation of Circuit Breaker pattern. When you apply the circuit breaker to a method, Hystrix watches for the failures of the method. Once failures build up to a threshold, Hystrix opens the circuit so that the subsequent calls also fail. Now Hystrix redirects calls to the method and they are passed to the specified fallback methods. Hystrix looks for any method annotated with the @HystrixCommand annotation and wraps it into a proxy connected to a circuit breaker so that Hystrix can monitor it.

Consider the following example:

Here @HystrixCommand is applied to the original method bookList() . The @HystrixCommand annotation has newList as the fallback method. So for some reason if Hystrix opens the circuit on bookList() , you will have a placeholder book list ready for the users.

Spring Framework DataAccess Annotations

@transactional.

This annotation is placed before an interface definition, a method on an interface, a class definition, or a public method on a class. The mere presence of @Transactional is not enough to activate the transactional behaviour. The @Transactional is simply a metadata that can be consumed by some runtime infrastructure. This infrastructure uses the metadata to configure the appropriate beans with transactional behaviour.

The annotation further supports configuration like:

  • The Propagation type of the transaction
  • The Isolation level of the transaction
  • A timeout for the operation wrapped by the transaction
  • A read only flag – a hint for the persistence provider that the transaction must be read only The rollback rules for the transaction

Cache-Based Annotations

This annotation is used on methods. The simplest way of enabling the cache behaviour for a method is to annotate it with @Cacheable and parameterize it with the name of the cache where the results would be stored.

In the snippet above , the method getAddress is associated with the cache named addresses. Each time the method is called, the cache is checked to see whether the invocation has been already executed and does not have to be repeated.

This annotation is used on methods. Whenever you need to update the cache without interfering the method execution, you can use the @CachePut annotation. That is, the method will always be executed and the result cached.

Using @CachePut and @Cacheable on the same method is strongly discouraged as the former forces the execution in order to execute a cache update, the latter causes the method execution to be skipped by using the cache.

@CacheEvict

This annotation is used on methods. It is not that you always want to populate the cache with more and more data. Sometimes you may want remove some cache data so that you can populate the cache with some fresh values. In such a case use the @CacheEvict annotation.

Here an additional element allEntries is used along with the cache name to be emptied. It is set to true so that it clears all values and prepares to hold new data.

@CacheConfig

This annotation is a class level annotation. The @CacheConfig annotation helps to streamline some of the cache information at one place. Placing this annotation on a class does not turn on any caching operation. This allows you to store the cache configuration at the class level so that you don’t have declare things multiple times.

Task Execution and Scheduling Annotations

This annotation is a method level annotation. The @Scheduled annotation is used on methods along with the trigger metadata. A method with @Scheduled should have void return type and should not accept any parameters.

There are different ways of using the @Scheduled annotation:

In this case, the duration between the end of last execution and the start of next execution is fixed. The tasks always wait until the previous one is finished.

In this case, the beginning of the task execution does not wait for the completion of the previous execution.

The task gets executed initially with a delay and then continues with the specified fixed rate.

This annotation is used on methods to execute each method in a separate thread. The @Async annotation is provided on a method so that the invocation of that method will occur asynchronously. Unlike methods annotated with @Scheduled , the methods annotated with @Async can take arguments. They will be invoked in the normal way by callers at runtime rather than by a scheduled task.

@Async can be used with both void return type methods and the methods that return a value. However methods with return value must have a Future typed return values.

Spring Framework Testing Annotations

@bootstrapwith.

This annotation is a class level annotation. The @BootstrapWith annotation is used to configure how the Spring TestContext Framework is bootstrapped. This annotation is used as a metadata to create custom composed annotations and reduce the configuration duplication in a test suite.

@ContextConfiguration

This annotation is a class level annotation that defines a metadata used to determine which configuration files to use to the load the ApplicationContext for your test. More specifically @ContextConfiguration declares the annotated classes that will be used to load the context. You can also tell Spring where to locate for the file. @ContextConfiguration(locations={"example/test-context.xml", loader = Custom ContextLoader.class})

@WebAppConfiguration

This annotation is a class level annotation. The @WebAppConfiguration is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. This annotation is used to create the web version of the application context. It is important to note that this annotation must be used with the @ContextConfiguration annotation.The default path to the root of the web application is src/main/webapp. You can override it by passing a different path to the @WebAppConfiguration .

This annotation is used on methods. The @Timed annotation indicates that the annotated test method must finish its execution at the specified time period(in milliseconds). If the execution exceeds the specified time in the annotation, the test fails.

In this example, the test will fail if it exceeds 10 seconds of execution.

This annotation is used on test methods. If you want to run a test method several times in a row automatically, you can use the @Repeat annotation. The number of times that test method is to be executed is specified in the annotation.

In this example, the test will be executed 10 times.

This annotation can be used as both class-level or method-level annotation. After execution of a test method, the transaction of the transactional test method can be committed using the @Commit annotation. This annotation explicitly conveys the intent of the code. When used at the class level, this annotation defines the commit for all test methods within the class. When declared as a method level annotation @Commit specifies the commit for specific test methods overriding the class level commit.

This annotation can be used as both class-level and method-level annotation. The @RollBack annotation indicates whether the transaction of a transactional test method must be rolled back after the test completes its execution. If this true @Rollback(true) , the transaction is rolled back. Otherwise, the transaction is committed. @Commit is used instead of @RollBack(false) .

When used at the class level, this annotation defines the rollback for all test methods within the class.

When declared as a method level annotation @RollBack specifies the rollback for specific test methods overriding the class level rollback semantics.

@DirtiesContext

This annotation is used as both class-level and method-level annotation. @DirtiesContext indicates that the Spring ApplicationContext has been modified or corrupted in some manner and it should be closed. This will trigger the context reloading before execution of next test. The ApplicationContext is marked as dirty before or after any such annotated method as well as before or after current test class.

The @DirtiesContext annotation supports BEFORE_METHOD , BEFORE_CLASS , and BEFORE_EACH_TEST_METHOD modes for closing the ApplicationContext before a test.

NOTE : Avoid overusing this annotation. It is an expensive operation and if abused, it can really slow down your test suite.

@BeforeTransaction

This annotation is used to annotate void methods in the test class. @BeforeTransaction annotated methods indicate that they should be executed before any transaction starts executing. That means the method annotated with @BeforeTransaction must be executed before any method annotated with @Transactional .

@AfterTransaction

This annotation is used to annotate void methods in the test class. @AfterTransaction annotated methods indicate that they should be executed after a transaction ends for test methods. That means the method annotated with @AfterTransaction must be executed after the method annotated with @Transactional .

This annotation can be declared on a test class or test method to run SQL scripts against a database. The @Sql annotation configures the resource path to SQL scripts that should be executed against a given database either before or after an integration test method. When @Sql is used at the method level it will override any @Sql defined in at class level.

This annotation is used along with the @Sql annotation. The @SqlConfig annotation defines the metadata that is used to determine how to parse and execute SQL scripts configured via the @Sql annotation. When used at the class-level, this annotation serves as global configuration for all SQL scripts within the test class. But when used directly with the config attribute of @Sql , @SqlConfig serves as a local configuration for SQL scripts declared.

This annotation is used on methods. The @SqlGroup annotation is a container annotation that can hold several @Sql annotations. This annotation can declare nested @Sql annotations. In addition, @SqlGroup is used as a meta-annotation to create custom composed annotations. This annotation can also be used along with repeatable annotations, where @Sql can be declared several times on the same method or class.

@SpringBootTest

This annotation is used to start the Spring context for integration tests. This will bring up the full autoconfigruation context.

@DataJpaTest

The @DataJpaTest annotation will only provide the autoconfiguration required to test Spring Data JPA using an in-memory database such as H2.

This annotation is used instead of @SpringBootTest

@DataMongoTest

The @DataMongoTest will provide a minimal autoconfiguration and an embedded MongoDB for running integration tests with Spring Data MongoDB.

@WebMVCTest

The @WebMVCTest will bring up a mock servlet context for testing the MVC layer. Services and components are not loaded into the context. To provide these dependencies for testing, the @MockBean annotation is typically used.

@AutoConfigureMockMVC

The @AutoConfigureMockMVC annotation works very similar to the @WebMVCTest annotation, but the full Spring Boot context is started.

Creates and injects a Mockito Mock for the given dependency.

Will limit the auto configuration of Spring Boot to components relevant to processing JSON.

This annotation will also autoconfigure an instance of JacksonTester or GsonTester .

@TestPropertySource

Class level annotation used to specify property sources for the test class.

  • spring framework annotations

' src=

You May Also Like

JWT Token Authentication in Spring Boot Microservices

JWT Token Authentication in Spring Boot Microservices

Spring Framework Guru

Hikari Configuration for MySQL in Spring Boot 2

Spring Framework Guru

Database Migration with Flyway

Spring Framework 6

Getting Ready for Spring Framework 6

Using Filters in Spring Web Applications

Using Filters in Spring Web Applications

Bootstrapping Data in Spring Boot

Bootstrapping Data in Spring Boot

Hikari Connection Pool

Eureka Service Registry

Spring Framework Guru

Scheduling in Spring Boot

Spring for Apache Kafka

Spring for Apache Kafka

Spring retry.

Spring Boot CLI

Spring Boot CLI

Spring Framework Guru

Actuator in Spring Boot

Internationalization with Spring Boot

Internationalization with Spring Boot

One-to-one relationship in jpa.

Spring Framework Guru

The @RequestBody Annotation

Learn Spring

Spring BeanFactory vs ApplicationContext

MySQL Stored Procedures with Spring Boot

MySQL Stored Procedures with Spring Boot

Spring Framework Guru

Bean Validation in Spring Boot

Spring state machine.

Exception Handling in Spring Boot REST API

Exception Handling in Spring Boot REST API

Spring Boot Pagination

Spring Boot Pagination

Spring rest docs, using mapstruct with project lombok, argumentcaptor in mockito.

Spring Framework Guru

Reading External Configuration Properties in Spring

Api gateway with spring cloud.

Testing Spring Boot RESTful Services

Testing Spring Boot RESTful Services

Caching in Spring RESTful Service: Part 2 - Cache Eviction

Caching in Spring RESTful Service: Part 2 – Cache Eviction

Spring boot messaging with rabbitmq.

Caching in Spring Boot RESTful Service: Part 1

Caching in Spring Boot RESTful Service: Part 1

Spring Framework Guru

Implementing HTTP Basic Authentication in a Spring Boot REST API

Immutable Property Binding

Immutable Property Binding

Java Bean Properties Binding

Java Bean Properties Binding

External configuration data in spring.

Spring Data JPA @Query

Spring Data JPA @Query

Configuring mysql with circleci.

Fabric8 Docker Maven Plugin

Fabric8 Docker Maven Plugin

Feign REST Client for Spring Application

Feign REST Client for Spring Application

Docker Hub for Spring Boot

Docker Hub for Spring Boot

Consul miniseries: spring boot application and consul integration part 3, run spring boot on docker, consul miniseries: spring boot application and consul integration part 2.

Consul Miniseries: Spring Boot Application and Consul Integration Part 1

Consul Miniseries: Spring Boot Application and Consul Integration Part 1

Why You Should be Using Spring Boot Docker Layers

Why You Should be Using Spring Boot Docker Layers

Spring Bean Scopes

Spring Bean Scopes

Debug your code in intellij idea, stay at home, learn from home with 6 free online courses.

What is the best UI to Use with Spring Boot?

What is the best UI to Use with Spring Boot?

Best Practices for Dependency Injection with Spring

Best Practices for Dependency Injection with Spring

Should I Use Spring REST Docs or OpenAPI?

Should I Use Spring REST Docs or OpenAPI?

Spring boot with lombok: part 1.

Spring Framework Guru

Using Project Lombok with Gradle

Spring bean lifecycle, spring profiles, spring bean definition inheritance, autowiring in spring.

spring boot

What is New in Spring Boot 2.2?

Using Ehcache 3 in Spring Boot

Using Ehcache 3 in Spring Boot

How to configure multiple data sources in a spring boot application.

Using RestTemplate with Apaches HttpClient

Using RestTemplate with Apaches HttpClient

Using RestTemplate in Spring

Using RestTemplate in Spring

Working with resources in spring, using spring aware interfaces, service locator pattern in spring, using graphql in a spring boot application, spring jdbctemplate crud operations, contracts for microservices with openapi and spring cloud contract, using swagger request validator to validate spring cloud contracts, spring 5 webclient, defining spring cloud contracts in open api.

Hibernate Show SQL

Hibernate Show SQL

Spring Component Scan

Spring Component Scan

Using CircleCI to Build Spring Boot Microservices

Using CircleCI to Build Spring Boot Microservices

Using JdbcTemplate with Spring Boot and Thymeleaf

Using JdbcTemplate with Spring Boot and Thymeleaf

Using the spring @requestmapping annotation.

Spring Data MongoDB with Reactive MongoDB

Spring Data MongoDB with Reactive MongoDB

Spring Boot with Embedded MongoDB

Spring Boot with Embedded MongoDB

Spring Web Reactive

Spring Web Reactive

What are Reactive Streams in Java?

What are Reactive Streams in Java?

Spring Framework 5

What’s new in Spring Framework 5?

Spring Boot RESTful API Documentation with Swagger 2

Spring Boot RESTful API Documentation with Swagger 2

Mockito Mock vs Spy in Spring Boot Tests

Mockito Mock vs Spy in Spring Boot Tests

Spring Boot Mongo DB Example Application

Spring Boot Mongo DB Example Application

Configuring Spring Boot for MariaDB

Configuring Spring Boot for MariaDB

Spring boot web application, part 6 – spring security with dao authentication provider.

Configuring Spring Boot for MongoDB

Configuring Spring Boot for MongoDB

Spring Boot Web Application, Part 5 - Spring Security

Spring Boot Web Application, Part 5 – Spring Security

Chuck Norris for Spring Boot Actuator

Chuck Norris for Spring Boot Actuator

Testing spring mvc with spring boot 1.4: part 1, running spring boot in a docker container.

Jackson Dependency Issue in Spring Boot with Maven Build

Jackson Dependency Issue in Spring Boot with Maven Build

Using YAML in Spring Boot to Configure Logback

Using YAML in Spring Boot to Configure Logback

Using Logback with Spring Boot

Using Logback with Spring Boot

Using Log4J 2 with Spring Boot

Using Log4J 2 with Spring Boot

Fixing nouniquebeandefinitionexception exceptions, samy is my hero and hacking the magic of spring boot.

2015 Year in Review

2015 Year in Review

Configuring Spring Boot for PostgreSQL

Configuring Spring Boot for PostgreSQL

Embedded JPA Entities Under Spring Boot and Hibernate Naming

Embedded JPA Entities Under Spring Boot and Hibernate Naming

Spring Boot Developer Tools

Spring Boot Developer Tools

Spring beanfactoryaware interface.

Spring BeanNameAware Interface

Spring BeanNameAware Interface

Displaying list of objects in table using thymeleaf.

Using H2 and Oracle with Spring Boot

Using H2 and Oracle with Spring Boot

Configuring Spring Boot for Oracle

Configuring Spring Boot for Oracle

Spring Boot Web Application - Part 4 - Spring MVC

Spring Boot Web Application – Part 4 – Spring MVC

Configuring Spring Boot for MySQL

Configuring Spring Boot for MySQL

Spring Boot Example of Spring Integration and ActiveMQ

Spring Boot Example of Spring Integration and ActiveMQ

How do i become a java web developer.

Spring Boot Web Application - Part 3 - Spring Data JPA

Spring Boot Web Application – Part 3 – Spring Data JPA

Spring Boot Web Application - Part 2 - Using ThymeLeaf

Spring Boot Web Application – Part 2 – Using ThymeLeaf

Spring Boot Web Application - Part 1 - Spring Initializr

Spring Boot Web Application – Part 1 – Spring Initializr

Using the H2 Database Console in Spring Boot with Spring Security

Using the H2 Database Console in Spring Boot with Spring Security

Running code on spring boot startup, integration testing with spring and junit.

polyglot programming

Polyglot Programming in Spring

Using Spring Integration Futures

Using Spring Integration Futures

Using the spring framework for enterprise application development.

Testing Spring Integration Gateways

Testing Spring Integration Gateways

Introduction to Spring Expression Language (SpEL)

Introduction to Spring Expression Language (SpEL)

Hello World Using Spring Integration

Hello World Using Spring Integration

Creating Spring Beans

Creating Spring Beans

Dependency Injection Example Using Spring

Dependency Injection Example Using Spring

Hello World With Spring 4

Hello World With Spring 4

Getting started with spring boot.

What's all the fuss about Java Lambdas?

What’s all the fuss about Java Lambdas?

36 comments on “ spring framework annotations ”.

' src=

Great summary, thanks. Bookmarked it (on DZone). I found two typos in the examples: @Configu_ar_tion and @Re_u_estMapping(“/cookieValue”)

' src=

stephanoapiolaza

Dear, Excelent documentation, thanks for this information

' src=

thanks for putting this together..

' src=

Thank you all th annotaions described very well!!!

' src=

Raviraj Darade

Nice information, Thanks !!!

' src=

Mustkeem mansuri

Yeh, its looking good but need to improve more details about annotations.

' src=

Simple, Nice and Excellent. Thanks

' src=

Ravindra Guvvala

good one ..Very helpful..

' src=

Rajeev Kumar Sharma

thanks for putting all together.

' src=

Raja Sekhar

Thank you very much. You have put all the information together.

' src=

Vikram Aditya

Thank you very much. We need this type of documentation where all the annotations described in one page.

' src=

Anamika Pandey

Thanks this was amazingly well put !

' src=

Cicciriello

Can I ask why exactly is a poor practice to autowire private fields? I’m new to spring and I’m trying to find my way of doing things

' src=

How do you set the property outside of the Spring Context? ie for a unit test? You can’t.

' src=

Ashish Kumar Singh

Nice explanation love to read… Can You provide more simple example

' src=

Thanks for the great article

' src=

It was very handy when we have all the list of annotations at one place.

' src=

raghu bhupatiraju

Very well done. Thanks!

' src=

A big help!

' src=

Good job !! @EnableJpaRepositories and @EntityScan are missing

' src=

Very good summary.

Though I came here to look for @EnableWebMvc, which I think needs to be included.

' src=

what ever is given spring annotation is correct but you should explain more annotations like @DependsOn.@value,@ComponentScan,@Order and etc .So you have to give more clarity about all anotations

' src=

Super explanation on each annotations …

Thanks it helped lots…

' src=

Mohammad Zeyaul

Hi This is really a great post but kind of a bit old. Can you please update this.

' src=

ravi ranjan

@EnableJpaRepositories It activates the spring JPA repositories defined in your spring-boot application. It carries same namespace as the XML namespace does.

' src=

What is the use of @transparent annotation ?

' src=

@EventListner? @TransactionEventListner?

Leave a Reply Cancel Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Spring Tutorial

Basics of Spring Framework

  • Introduction to Spring Framework
  • Spring Framework Architecture
  • 10 Reasons to Use Spring Framework in Projects
  • Spring Initializr
  • Difference Between Spring DAO vs Spring ORM vs Spring JDBC
  • Top 10 Most Common Spring Framework Mistakes
  • Spring vs. Struts in Java

Software Setup and Configuration

  • How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
  • How to Create and Setup Spring Boot Project in Spring Tool Suite?
  • How to Create a Spring Boot Project with IntelliJ IDEA?
  • How to Create and Setup Spring Boot Project in Eclipse IDE?
  • How to Create a Dynamic Web Project in Eclipse/Spring Tool Suite?
  • How to Run Your First Spring Boot Application in IntelliJ IDEA?
  • How to Run Your First Spring Boot Application in Spring Tool Suite?
  • How to Turn on Code Suggestion in Eclipse or Spring Tool Suite?

Core Spring

  • Spring - Understanding Inversion of Control with Example
  • Spring - BeanFactory
  • Spring - ApplicationContext
  • Spring - Difference Between BeanFactory and ApplicationContext
  • Spring Dependency Injection with Example
  • Spring - Difference Between Inversion of Control and Dependency Injection
  • Spring - Injecting Objects By Constructor Injection
  • Spring - Setter Injection with Map
  • Spring - Dependency Injection with Factory Method
  • Spring - Dependency Injection by Setter Method
  • Spring - Setter Injection with Non-String Map
  • Spring - Constructor Injection with Non-String Map
  • Spring - Constructor Injection with Map
  • Spring - Setter Injection with Dependent Object
  • Spring - Constructor Injection with Dependent Object
  • Spring - Setter Injection with Collection
  • Spring - Setter Injection with Non-String Collection
  • Spring - Constructor Injection with Collection
  • Spring - Injecting Objects by Setter Injection
  • Spring - Injecting Literal Values By Setter Injection
  • Spring - Injecting Literal Values By Constructor Injection
  • Bean life cycle in Java Spring
  • Custom Bean Scope in Spring
  • How to Create a Spring Bean in 3 Different Ways?
  • Spring - IoC Container
  • Spring - Autowiring
  • Singleton and Prototype Bean Scopes in Java Spring
  • How to Configure Dispatcher Servlet in web.xml File?
  • Spring - Configure Dispatcher Servlet in Three Different Ways
  • How to Configure Dispatcher Servlet in Just Two Lines of Code in Spring?
  • Spring - When to Use Factory Design Pattern Instead of Dependency Injection
  • How to Create a Simple Spring Application?
  • Spring - init() and destroy() Methods with Example
  • Spring WebApplicationInitializer with Example
  • Spring - Project Modules
  • Spring - Remoting by HTTP Invoker
  • Spring - Expression Language(SpEL)
  • Spring - Variable in SpEL
  • What is Ambiguous Mapping in Spring?
  • Spring - Add New Query Parameters in GET Call Through Configurations
  • Spring - Integrate HornetQ
  • Remoting in Spring Framework
  • Spring - Application Events
  • Spring c-namespace with Example
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Spring - AbstractRoutingDataSource
  • Circular Dependencies in Spring
  • Spring - ResourceLoaderAware with Example
  • Spring Framework Standalone Collections
  • How to Create a Project using Spring and Struts 2?
  • Spring - Perform Update Operation in CRUD
  • How to Transfer Data in Spring using DTO?
  • Spring - Resource Bundle Message Source (i18n)
  • Spring Application Without Any .xml Configuration
  • Spring - BeanPostProcessor
  • Spring and JAXB Integration
  • Spring - Difference Between Dependency Injection and Factory Pattern
  • Spring - REST Pagination
  • Spring - Remoting By Burlap
  • Spring - Remoting By Hessian
  • Spring with Castor Example
  • Spring - REST XML Response
  • Spring - Inheriting Bean
  • Spring - Change DispatcherServlet Context Configuration File Name
  • Spring - JMS Integration
  • Spring - Difference Between RowMapper and ResultSetExtractor
  • Spring with Xstream
  • Spring - RowMapper Interface with Example
  • Spring - util:constant
  • Spring - Static Factory Method
  • Spring - FactoryBean
  • Difference between EJB and Spring

Spring Framework Annotations

  • Spring Core Annotations
  • Spring - Stereotype Annotations
  • Spring @Bean Annotation with Example
  • Spring @Controller Annotation with Example
  • Spring @Value Annotation with Example
  • Spring @Configuration Annotation with Example
  • Spring @ComponentScan Annotation with Example
  • Spring @Qualifier Annotation with Example
  • Spring @Service Annotation with Example
  • Spring @Repository Annotation with Example
  • Spring - Required Annotation
  • Spring @Component Annotation with Example
  • Spring @Autowired Annotation
  • Spring - @PostConstruct and @PreDestroy Annotation with Example
  • Java Spring - Using @PropertySource Annotation and Resource Interface
  • Java Spring - Using @Scope Annotation to Set a POJO's Scope
  • Spring @Required Annotation with Example
  • Spring Boot Tutorial
  • Spring MVC Tutorial

Spring with REST API

  • Spring - REST JSON Response
  • Spring - REST Controller

Spring Data

  • What is Spring Data JPA?
  • Spring Data JPA - Find Records From MySQL
  • Spring Data JPA - Delete Records From MySQL
  • Spring Data JPA - @Table Annotation
  • Spring Data JPA - Insert Data in MySQL Table
  • Spring Data JPA - Attributes of @Column Annotation with Example
  • Spring Data JPA - @Column Annotation
  • Spring Data JPA - @Id Annotation
  • Introduction to the Spring Data Framework
  • Spring Boot | How to access database using Spring Data JPA
  • How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Spring JDBC

  • Spring - JDBC Template
  • Spring JDBC Example
  • Spring - SimpleJDBCTemplate with Example
  • Spring - Prepared Statement JDBC Template
  • Spring - NamedParameterJdbcTemplate
  • Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
  • Spring - ResultSetExtractor

Spring Hibernate

  • Spring Hibernate Configuration and Create a Table in Database
  • Hibernate Lifecycle
  • Java - JPA vs Hibernate
  • Spring ORM Example using Hibernate
  • Hibernate - One-to-One Mapping
  • Hibernate - Cache Eviction with Example
  • Hibernate - Cache Expiration
  • Hibernate - Enable and Implement First and Second Level Cache
  • Hibernate - Save Image and Other Types of Values to Database
  • Hibernate - Pagination
  • Hibernate - Different Cascade Types
  • Hibernate Native SQL Query with Example
  • Hibernate - Caching
  • Hibernate - @Embeddable and @Embedded Annotation
  • Hibernate - Eager/Lazy Loading
  • Hibernate - get() and load() Method
  • Hibernate Validator
  • CRUD Operations using Hibernate
  • Hibernate Example without IDE
  • Hibernate - Inheritance Mapping
  • Automatic Table Creation Using Hibernate
  • Hibernate - Batch Processing
  • Hibernate - Component Mapping
  • Hibernate - Mapping List
  • Hibernate - Collection Mapping
  • Hibernate - Bag Mapping
  • Hibernate - Difference Between List and Bag Mapping
  • Hibernate - SortedSet Mapping
  • Hibernate - SortedMap Mapping
  • Hibernate - Native SQL
  • Hibernate - Logging by Log4j using xml File
  • Hibernate - Many-to-One Mapping
  • Hibernate - Logging By Log4j Using Properties File
  • Hibernate - Table Per Concrete Class Using Annotation
  • Hibernate - Table Per Subclass using Annotation
  • Hibernate - Interceptors
  • Hibernate - Many-to-Many Mapping
  • Hibernate - Types of Mapping
  • Hibernate - Criteria Queries
  • Hibernate - Table Per Hierarchy using Annotation
  • Hibernate - Table Per Subclass Example using XML File
  • Hibernate - Table Per Hierarchy using XML File
  • Hibernate - Create POJO Classes
  • Hibernate - Web Application
  • Hibernate - Table Per Concrete Class using XML File
  • Hibernate - Generator Classes
  • Hibernate - SQL Dialects
  • Hibernate - Query Language
  • Hibernate - Difference Between ORM and JDBC
  • Hibernate - Annotations
  • Hibernate Example using XML in Eclipse
  • Hibernate - Create Hibernate Configuration File with the Help of Plugin
  • Hibernate Example using JPA and MySQL
  • Hibernate - One-to-Many Mapping
  • Aspect Oriented Programming and AOP in Spring Framework
  • Spring - AOP Example (Spring1.2 Old Style AOP)
  • Spring - AOP AspectJ Xml Configuration
  • Spring AOP - AspectJ Annotation
  • Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project

Spring Security

  • Introduction to Spring Security and its Features
  • Some Important Terms in Spring Security
  • OAuth2 Authentication with Spring and Github
  • Spring Security at Method Level
  • Spring - Security JSP Tag Library
  • Spring - Security Form-Based Authentication
  • Spring Security - Remember Me
  • Spring Security XML
  • Spring Security Project Example using Java Configuration
  • How to Change Default User and Password in Spring Security?
  • Spring - Add Roles in Spring Security
  • Spring - Add User Name and Password in Spring Security

Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. So in this article, we are going to discuss what are the main types of annotation that are available in the spring framework with some examples. 

Types of Spring Framework Annotations

Basically, there are 6 types of annotation available in the whole spring framework.

  • Spring Web Annotations
  • Spring Boot Annotations
  • Spring Scheduling Annotations
  • Spring Data Annotations
  • Spring Bean Annotations

Type 1: Spring Core Annotations 

Spring annotations present in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages are commonly known as Spring Core annotations. We can divide them into two categories:

  • @Lookup, etc.
  • @ImportResource
  • @PropertySource, etc.

A DI (Dependency Injection) Related Annotations

1.1: @Autowired

@Autowired annotation is applied to the fields, setter methods, and constructors. It injects object dependency implicitly. We use @Autowired to mark the dependency that will be injected by the Spring container.

1.2: Field injection

1.3: Constructor injection

 

1.4: Setter injection

B Context Configuration Annotations  

@Profile: If you want Spring to use a @Component class or a @Bean method only when a specific profile is active then you can mark it with @Profile. 

Type 2: Spring Web Annotations

Spring annotations present in the org.springframework.web.bind.annotation p ackages are commonly known as Spring Web annotations. Some of the annotations that are available in this category are:

  • @RequestMapping
  • @RequestBody
  • @PathVariable
  • @RequestParam
  • @ResponseBody
  • @ExceptionHandler
  • @ResponseStatus
  • @Controller
  • @RestController
  • @ModelAttribute
  • @CrossOrigin

Example: @Controller

Spring @Controller annotation is also a specialization of @Component annotation. The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It’s used to mark a class as a web request handler. It’s mostly used with Spring MVC applications. This annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

     

Type 3: Spring Boot Annotations

Spring annotations present in the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.condition packages are commonly known as Spring Boot annotations. Some of the annotations that are available in this category are:

  • @SpringBootApplication
  • @EnableAutoConfiguration
  • @ConditionalOnClass, and @ConditionalOnMissingClass
  • @ConditionalOnBean, and @ConditionalOnMissingBean
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
  • @ConditionalExpression
  • @Conditional

Example: @SpringBootApplication

This annotation is used to mark the main class of a Spring Boot application. It encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes.

     

Type 4: Spring Scheduling Annotations

Spring annotations present in the org.springframework.scheduling.annotation packages are commonly known as Spring Scheduling annotations. Some of the annotations that are available in this category are:

  • @EnableAsync
  • @EnableScheduling

Example: @EnableAsync

This annotation is used to enable asynchronous functionality in Spring.

Type 5: Spring Data Annotations

Spring Data provides an abstraction over data storage technologies. Hence the business logic code can be much more independent of the underlying persistence implementation. Some of the annotations that are available in this category are:

  • @Transactional
  • @NoRepositoryBean
  • @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
  • @EnableJpaRepositories
  • @EnableMongoRepositories

A @Transactional  

When there is a need to configure the transactional behavior of a method, we can do it with @Transactional annotation. 

B @Id: @Id marks a field in a model class as the primary key. Since it’s implementation-independent, it makes a model class easy to use with multiple data store engines.

Type 6: Spring Bean Annotations

There’re several ways to configure beans in a Spring container. You can declare them using XML configuration or you can declare beans using the @Bean annotation in a configuration class or you can mark the class with one of the annotations from the org.springframework.stereotype package and leave the rest to component scanning. Some of the annotations that are available in this category are:

  • @ComponentScan
  • @Configuration
  • @Repository

Example: Stereotype Annotations

Spring Framework provides us with some special annotations. These annotations are used to create Spring beans automatically in the application context. @Component annotation is the main Stereotype Annotation. There are some Stereotype meta-annotations which is derived from @Component those are

1: @Service: We specify a class with @Service to indicate that they’re holding the business logic. Besides being used in the service layer, there isn’t any other special use for this annotation. The utility classes can be marked as Service classes.

2: @Repository: We specify a class with @Repository to indicate that they’re dealing with CRUD operations , usually, it’s used with DAO (Data Access Object) or Repository implementations that deal with database tables.

3: @Controller: We specify a class with @Controller to indicate that they’re front controllers and responsible to handle user requests and return the appropriate response. It is mostly used with REST Web Services.

So the stereotype annotations in spring are @Component, @Service, @Repository, and @Controller .

annotation list spring

Please Login to comment...

Similar reads.

  • Java-Spring

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Tutorial World

List of All Spring Boot Annotations, Uses with examples

  • Post author: Tutorial World
  • Post published:
  • Post category: Spring Boot

Table of Contents

Commonly used Spring Boot annotations along with their uses and examples

1). @SpringBootApplication: This annotation is used to bootstrap a Spring Boot application. It combines three annotations: @Configuration , @EnableAutoConfiguration , and @ComponentScan .

2). @RestController: This annotation is used to indicate that a class is a RESTful controller. It combines @Controller and @ResponseBody .

3). @RequestMapping: This annotation is used to map web requests to specific handler methods. It can be applied at the class or method level.

4). @Autowired: This annotation is used to automatically wire dependencies in Spring beans. It can be applied to fields, constructors, or methods.

5). @Component: This annotation is used to indicate that a class is a Spring bean. Example:

6). @Service: This annotation is used to indicate that a class is a specialized type of Spring bean, typically used for business logic.

7). @Repository: This annotation is used to indicate that a class is a specialized type of Spring bean, typically used for database access.

8). @Configuration: This annotation is used to declare a class as a configuration class. It is typically used in combination with @Bean methods.

9). @Value: This annotation is used to inject values from properties files or other sources into Spring beans.

10). @EnableAutoConfiguration: This annotation is used to enable Spring Boot’s auto-configuration mechanism. It automatically configures the application based on the classpath dependencies and properties.

11). @GetMapping, @PostMapping, @PutMapping, @DeleteMapping : These annotations are used to map specific HTTP methods to handler methods. They are shortcuts for <strong>@RequestMapping</strong> with the respective HTTP method.

12). @PathVariable: This annotation is used to bind a method parameter to a path variable in a request URL.

13). @RequestParam: This annotation is used to bind a method parameter to a request parameter.

14). @RequestBody: This annotation is used to bind the request body to a method parameter. It is commonly used in RESTful APIs to receive JSON or XML payloads. Example:

15). @Qualifier: This annotation is used to specify which bean to inject when multiple beans of the same type are available.

16). @ConditionalOnProperty: This annotation is used to conditionally enable or disable a bean or configuration based on the value of a property.

17). @Scheduled: This annotation is used to schedule the execution of a method at fixed intervals.

18). @Cacheable, @CachePut, @CacheEvict: These annotations are used for caching method results. They allow you to cache the return value of a method, update the cache, or evict the cache, respectively.

Here’s an extensive list of Spring Boot annotations

1. core annotations:, a). @springbootapplication.

The @SpringBootApplication annotation is used to mark the main class of a Spring Boot application. This is the Spring Boot Application starting point. It combines three annotations: @Configuration , @EnableAutoConfiguration , and @ComponentScan . This annotation enables auto-configuration, component scanning, and configuration capabilities for the application.

b). @ComponentScan

The @ComponentScan annotation is used to specify the base package(s) to scan for Spring components such as controllers, services, repositories, etc.

c). @Configuration

The @Configuration annotation is used to indicate that a class declares one or more bean definitions. It is typically used in combination with @Bean to define Spring configuration classes. In the example, the DatabaseConfig class is marked as a configuration class, and the dataSource() method is annotated with @Bean to define a bean of type DataSource .

d). @EnableAutoConfiguration

The @EnableAutoConfiguration annotation allows Spring Boot to automatically configure the application based on the dependencies present in the classpath. It helps to reduce manual configuration by inferring configuration based on conventions and default settings.

e). @RestController

The @RestController annotation is used to mark a class as a controller in a Spring MVC or Spring WebFlux application. It combines the @Controller and @ResponseBody annotations. In the example, the UserController class is a REST controller that handles HTTP GET requests for the “/users” endpoint.

f). @Controller

The @Controller annotation is used to mark a class as a controller in a Spring MVC or Spring WebFlux application. It handles HTTP requests and returns the view name or a response body. In the example, the HomeController class is a controller that handles requests for the root (“/”) URL and returns the view name “index”.

g). @Service

The @Service annotation is used to mark a class as a service component in the business logic layer. It is used to encapsulate business logic and perform operations such as data retrieval, manipulation, and validation. In the example, the UserService class is a service component that provides a method to retrieve users.

h). @Repository

The @Repository annotation is used to mark a class as a repository component in the data access layer. It is responsible for data access operations such as querying, saving, updating, and deleting data from a database. In the example, the UserRepository class is a repository component that provides a method to retrieve users from the database.

The @Bean annotation is used to declare a method as a bean producer method within a configuration class. It indicates that the method returns an object that should be managed by the Spring container as a bean. In the example, the userService() method is annotated with @Bean to define a bean of type UserService .

j). @Autowired

The @Autowired annotation is used to inject dependencies automatically by type. It can be applied to constructors, fields, and methods. In the example, the UserRepository dependency is autowired into the UserService class constructor.

k). @Qualifier

The @Qualifier annotation is used to resolve ambiguous dependencies when there are multiple beans of the same type. It can be applied along with @Autowired to specify the exact bean to be injected. In the example, the userRepository bean is qualified using its bean name.

The @Value annotation is used to inject values from external sources, such as properties files, into variables. In the example, the appName the variable is injected with the value of the “app.name” property from an external configuration source.

2. Web Annotations :

@RequestMapping

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

@PatchMapping

@RequestBody

@ResponseBody

@PathVariable

@RequestParam

@RequestHeader

@CookieValue

@ModelAttribute

@ResponseStatus

@ExceptionHandler

3. Data Annotations :

@GeneratedValue

@Repository

@Transactional

@PersistenceContext

@NamedQuery

@JoinColumn

4. Validation Annotations :

5. security annotations :.

@EnableWebSecurity

@Configuration

@EnableGlobalMethodSecurity

@PreAuthorize

@PostAuthorize

@RolesAllowed

@EnableOAuth2Client

@EnableResourceServer

@EnableAuthorizationServer

6. Testing Annotations :

@SpringBootTest

@WebMvcTest

@DataJpaTest

@RestClientTest

@AutoConfigureMockMvc

@BeforeEach

@DisplayName

@ParameterizedTest

@ValueSource

@ExtendWith

7. Caching Annotations :

@EnableCaching

@CacheEvict

8. Scheduling Annotations :

@EnableScheduling

9. Messaging Annotations :

@JmsListener

@MessageMapping

10. Aspect-Oriented Programming (AOP) Annotations :

@AfterReturning

@AfterThrowing

11. Actuator Annotations :

@EnableActuator

@RestControllerEndpoint

@ReadOperation

@WriteOperation

@DeleteOperation

12. Configuration Properties Annotations :

@ConfigurationProperties

@ConstructorBinding

13. Internationalization and Localization :

@EnableMessageSource

@EnableWebMvc

@LocaleResolver

@MessageBundle

@MessageSource

14. Logging and Monitoring :

@ExceptionMetered

15. Data Validation :

@PositiveOrZero

@NegativeOrZero

16. GraphQL Annotations :

@GraphQLApi

@GraphQLQuery

@GraphQLMutation

@GraphQLSubscription

@GraphQLArgument

@GraphQLContext

@GraphQLNonNull

@GraphQLInputType

@GraphQLType

17. Integration Annotations :

@IntegrationComponentScan

@MessagingGateway

@Transformer

@Aggregator

@ServiceActivator

@InboundChannelAdapter

@OutboundChannelAdapter

18. Flyway Database Migrations :

@FlywayTest

@FlywayTestExtension

@FlywayTestExtension.Test

@FlywayTestExtension.BeforeMigration

@FlywayTestExtension.AfterMigration

19. JUnit 5 Annotations :

@TestInstance

@TestTemplate

@DisplayNameGeneration

@DisabledOnOs

@EnabledOnOs

@DisabledIf

20. API Documentation Annotations :

@Api: This annotation is used to provide high-level information about the API.

@ApiOperation: This annotation is used to describe an operation or endpoint in the API.

@ApiParam: This annotation is used to describe a parameter in an API operation.

@ApiModel: This annotation is used to describe a data model used in the API.

@ApiModelProperty: This annotation is used to describe a property of a data model.

21. Exception Handling Annotations :

@ControllerAdvice: This annotation is used to define global exception handling for controllers.

@ExceptionHandler: This annotation is used to define a method to handle specific exceptions.

22. GraphQL Annotations :

@GraphQLSchema: This annotation is used to define the GraphQL schema for a Spring Boot application.

@GraphQLQueryResolver: This annotation is used to define a class as a GraphQL query resolver.

@GraphQLMutationResolver: This annotation is used to define a class as a GraphQL mutation resolver.

@GraphQLSubscriptionResolver: This annotation is used to define a class as a GraphQL subscription resolver.

@GraphQLResolver: This annotation is used to define a class as a generic resolver for GraphQL.

23. Server-Sent Events (SSE) Annotations :

@SseEmitter: This annotation is used to create an SSE endpoint for server-sent events.

@SseEventSink: This annotation is used to inject an SSE event sink into a method parameter.

24. WebFlux Annotations :

@RestController: This annotation is used to create a RESTful controller in a WebFlux application.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping: These annotations are used to map HTTP methods to handler methods in a WebFlux application.

25. Micrometer Metrics Annotations :

@Timed: This annotation is used to measure the execution time of a method.

@Counted: This annotation is used to count the number of times a method is invoked.

@Gauge: This annotation is used to expose a method as a gauge metric.

@ExceptionMetered: This annotation is used to measure the rate of exceptions thrown by a method.

Please note that this is not an exhaustive list, and Spring Boot offers many more annotations across various modules and features. For a comprehensive list of annotations and their usage, I recommend referring to the official Spring Boot documentation and module-specific documentation.

You Might Also Like

5 ways for spring configuration in spring boot application, spring beans and bean scopes explanation, explain spring boot data for working with databases.

Annotations

This section covers annotations that you can use when you test Spring applications.

Section Summary

  • Standard Annotation Support
  • Spring Testing Annotations
  • Spring JUnit 4 Testing Annotations
  • Spring JUnit Jupiter Testing Annotations
  • Meta-Annotation Support for Testing
  • 6.2.0-SNAPSHOT
  • 6.1.11-SNAPSHOT
  • 6.1.10 current
  • 6.0.23-SNAPSHOT
  • Spring Boot
  • Spring Framework
  • Spring Cloud Build
  • Spring Cloud Bus
  • Spring Cloud Circuit Breaker
  • Spring Cloud Commons
  • Spring Cloud Config
  • Spring Cloud Consul
  • Spring Cloud Contract
  • Spring Cloud Function
  • Spring Cloud Gateway
  • Spring Cloud Kubernetes
  • Spring Cloud Netflix
  • Spring Cloud OpenFeign
  • Spring Cloud Stream
  • Spring Cloud Task
  • Spring Cloud Vault
  • Spring Cloud Zookeeper
  • Spring Data Cassandra
  • Spring Data Commons
  • Spring Data Couchbase
  • Spring Data Elasticsearch
  • Spring Data JPA
  • Spring Data KeyValue
  • Spring Data LDAP
  • Spring Data MongoDB
  • Spring Data Neo4j
  • Spring Data Redis
  • Spring Data JDBC & R2DBC
  • Spring Data REST
  • Spring Integration
  • Spring Batch
  • Spring Authorization Server
  • Spring LDAP
  • Spring Security Kerberos
  • Spring Session
  • Spring Vault
  • Spring AMQP
  • Spring GraphQL
  • Spring for Apache Kafka
  • Spring Modulith
  • Spring for Apache Pulsar
  • Spring Shell
  • All Docs...

Lightrun

  • 25-Jul-2022
  • debugging , Dev Tools , Java

Lightrun Team

The Essential List of Spring Boot Annotations and Their Use Cases

  • debugging Dev Tools Java

The Spring framework is a robust server-side framework for modern Java-based enterprise applications. Since its introduction in 2003, its advantages have made it one of the most dominant server-side frameworks among many organizations. According to a research study by Snyk in 2020 on the usage of the server-side web frameworks , 50% of the respondents have said they use Spring Boot , and 31% of the respondents use Spring MVC. 

Java applications use annotations to provide additional information about the code but do not impact a compiled code. They usually start with ‘@’ and are metadata associated with code components such as variables, methods, classes, etc. Based on the defined annotations, the compiler can change how it treats the program.

What is Java Spring Boot?

Java Spring Boot is an open-source framework that allows the creation of standalone and production-grade enterprise applications that execute on Java Virtual Machine (JVM).

Spring Boot has three core capabilities that enable the development of web applications and microservices faster and easier. 

  • Autoconfiguration
  • An opinionated approach to configuration
  • The ability to create standalone applications

You can configure and set up Spring Boot applications with minimal changes from these core capabilities. Any production application needs to be monitored for its uptime. You can use Spring Boot Actuator as a dependency to simplify monitoring your application’s status. 

Spring Boot Features

Why use Annotations? 

Annotations are not just comments in a program. There are many uses of annotations. Annotations help to provide helpful information such as method dependencies, variable meanings, class references, package declaration, type declaration, and many more. Also, they help developers understand the code easily. The compiler can catch errors and suppress specific warnings using annotations. It allows static type checking at compile time. Developers can use these annotations for further processing, such as creating XML files and codes, and with annotations, developers do not have to do cumbersome configurations.

Spring Boot Annotations and their use cases

Spring Boot Annotations are the metadata that provides the additional formation about a Spring Boot program. Several spring boot annotations provide different automatic configurations.

Below are all the essential spring boot annotations you should know about.

The “@Bean” is a method-level annotation that is analogous to XML <bean> tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory. The following shows how the usage of @Bean in a method statement:

2. @Springbootapplication

The “@SpringBootApplication” annotation triggers auto-configuration and component scanning. It combines three annotations: @Configuration, @ComponentScan, and @EnabeAutoConfiguration. 

3. @Configuration

The “@Configuration” is a class-based annotation that indicates the definition of one or more Bean methods in the class. Once the Sprint container encounters this annotation, it can process these spring beans to generate bean definitions and service requests at runtime.

4. @ComponentScan

You can use the “@ComponentScan” annotation with the “@Configuration” annotation to define the components you need the program to scan. There are a few arguments in this annotation. The framework scans the current package with sub-packages if you do not specify any argument. You can use the ‘basePackages’ argument to define the specific packages to scan.

5. @EnableAutoconfiguration

This annotation allows you to auto-configure the program based on your requirements. The framework decides this auto-configuration based on the jars included in the program and the classpath. For example, suppose you added the “tomcat-embedded.jar” file, then it automatically configures the TomcatServletWebServerFactory if there is no explicit declaration for its related factory bean. Using the “exclude” and “excludeClassName” arguments.

6. @RequestMapping 

The “@RequestMapping” Annotation is used to map HTTP requests to REST and MVC controller methods in Spring Boot applications. You can apply this to either class-level or method-level in a controller. Furthermore, you can declare multiple request mappings using a list of values in the annotation.

7. @GetMapping 

The “@GetMapping” is a shortcut for the  “@RequestMapping(method = RequestMethod.GET)” annotation, which handles the HTTP GET requests corresponding to the specified URL. The following class uses the “@RestController” annotation to indicate it can handle web requests. The “@GetMapping” maps /hello to the hello() method

8. @RequestParam

The “@RequestParam” annotation enables extracting input query parameters, form data, etc. For example, suppose you have an endpoint /API/book which takes a query string parameter called id. Then you can specify that parameter in the following manner using the @RequestParam annotation. 

9. @Service 

The @Service is a class-level annotation used to indicate that the class is a service class that defines the business logic. For instance, the below @Service annotation indicates that BankService is a service class that offers bank services. 

10. @Component 

This component allows the framework to automatically detect the component classes without any need to write any explicit code. Spring framework scans classes with @component, initialize them, and injects the required dependencies.

11. @Repository

The “@Repository” is a specialized version of the “ @Component” annotation. It indicates that the class is a repository that contains data storage and other operations such as updating, deleting, searching, and retrieving data on objects. 

12. @Controller

This class-based annotation is also a specialization of the “@Component” annotation, marking the class as a controller. It usually combines with handler methods annotated with the @RequestMapping annotation and is used with Spring MVC applications. Spring scans these classes with this annotation and catches @RequestMapping annotations. Below is an example of its usage.

13. @Autowired

The “@Autowired” annotation can auto wire bean on a constructor,  setter method, property, or methods with multiple parameters. When you use @Autowired annotation on setter methods, you can eliminate the <property> tag in the XML configuration file. 

14. @SpringBootTest

As the name suggests, @SpringBootTest annotation can be used on a test class that executes Spring Boot-based tests. You can use it easily for integration testing as it loads the full application context. 

15. @MockBean

Using this annotation, you can specify mocks in ApplicationContext and mocks the services or REST API endpoints from your programs. Spring loads the mock version of the application context when you run the application. You can specify this annotation at the class and field levels, and it is possible to specify them in configuration classes. Below is an example of using the “@MockBean” annotation.

Spring Boot has a collection of annotations that enable you to develop web applications faster and more efficiently. While developing with Spring Boot,  speed and productivity are absolute priorities for all developers. Lightrun is a key observability platform that helps developers build applications faster by enabling them to add logs, traces, and metrics to their code on-demand and in real-time while the app runs.

Do you want to build robust and fast-running applications? Then get started with Lightrun or request a demo today!

Observability vs monitoring

Observability vs. Monitoring

Top IntelliJ debug shortcuts

Top 8 IntelliJ Debug Shortcuts

Shift left testing

Shift Left Testing: 6 Essentials for Successful Implementation

It’s really not that complicated..

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Looking for more information about Lightrun and debugging? We’d love to hear from you! Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use .

Java Guides

Java Guides

Search this blog, java, java ee, spring and spring boot annotations with examples.

This page contains a one-stop shop for commonly used Java, Java EE, Spring, and Spring Boot annotations with examples. Each annotation is explained with source code examples and its usage.

1. Spring Core Annotations

List of Spring core annotations tutorials

@Component Annotation

The @Component annotation indicates that an annotated class is a “spring bean/component”. The @Component annotation tells the Spring container to automatically create Spring bean.

@Autowired Annotation

The @Autowired annotation is used to inject the bean automatically. The @Autowired annotation is used in constructor injection, setter injection, and field injection

@Qualifier Annotation

@Qualifier annotation is used in conjunction with Autowired to avoid confusion when we have two or more beans configured for the same type.

@Primary Annotation

We use @Primary annotation to give higher preference to a bean when there are multiple beans of the same type.

@Bean Annotation

@Bean annotation indicates that a method produces a bean to be managed by the Spring container. The @Bean annotation is usually declared in the Configuration class to create Spring Bean definitions.

@Lazy Annotation

By default, Spring creates all singleton beans eagerly at the startup/bootstrapping of the application context. You can load the Spring beans lazily (on-demand) using @Lazy annotation.

@Scope Annotation

The @Scope annotation is used to define the scope of the bean. We use @Scope to define the scope of a @Component class or a @Bean definition.

@Value Annotation

Spring @Value annotation is used to assign default values to variables and method arguments. @Value annotation is mostly used to get value for specific property keys from the properties file.

@PropertySource Annotation

Spring @PropertySource annotation is used to provide properties files to Spring Environment.

2. Spring MVC Web Annotations

List of Spring MVC annotations tutorials

@Controller Annotation

Spring provides @Controller annotation to make a Java class as a Spring MVC controller. The @Controller annotation indicates that a particular class serves the role of a controller.

@ResponseBody Annotation

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

@RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the @Controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations.

@RequestMapping Annotation

@RequestMapping is the most common and widely used annotation in Spring MVC. It is used to map web requests onto specific handler classes and/or handler methods.

@GetMapping Annotation

The GET HTTP request is used to get single or multiple resources and @GetMapping annotation for mapping HTTP GET requests onto specific handler methods.

@PostMapping Annotation

The POST HTTP method is used to create a resource and @PostMapping annotation for mapping HTTP POST requests onto specific handler methods.

@PutMapping Annotation

The PUT HTTP method is used to update the resource and @PutMapping annotation for mapping HTTP PUT requests onto specific handler methods.

@DeleteMapping Annotation

The DELETE HTTP method is used to delete the resource and @DeleteMapping annotation for mapping HTTP DELETE requests onto specific handler methods.

@PatchMapping Annotation

The PATCH HTTP method is used to update the resource partially and the @PatchMapping annotation is for mapping HTTP PATCH requests onto specific handler methods.

@PathVariable Annotation

Spring boot @PathVariable annotation is used on a method argument to bind it to the value of a URI template variable.

@ResponseStatus Annotation

The @ResponseStatus annotation is a Spring Framework annotation that is used to customize the HTTP response status code returned by a controller method in a Spring MVC or Spring Boot application.

@Service Annotation

@Service annotation is used to create Spring beans at the Service layer.

@Repository Annotation

@Repository is used to create Spring beans for the repositories at the DAO layer.

@Controller is used to create Spring beans at the controller layer.

3. Spring Boot Annotations

List of Spring Boot Annotations tutorials

@SpringBootApplication annotation

The @SpringBootApplication annotation is a core annotation in the Spring Boot framework. It is used to mark the main class of a Spring Boot application.

@EnableAutoConfiguration annotation

@EnableAutoConfiguration annotation enables Spring Boot's auto-configuration feature, which automatically configures the application based on the classpath dependencies and the environment.

@Async Annotation

The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously.

@Scheduled Annotation

The @Scheduled annotation is added to a method along with some information about when to execute it, and Spring takes care of the rest.

@SpringBootTest annotation

Spring Boot provides @SpringBootTest annotation for Integration testing. This annotation creates an application context and loads the full application context.

@WebMvcTest annotation

The @WebMvcTest annotation is used to perform unit tests on Spring MVC controllers. It allows you to test the behavior of controllers, request mappings, and HTTP responses in a controlled and isolated environment.

4. Spring Data JPA Annotations

List of 4. Spring Data JPA Annotations tutorials

@Query Annotation

In Spring Data JPA, the @Query annotation is used to define custom queries. It allows developers to execute both JPQL (Java Persistence Query Language) and native SQL queries.

@DataJpaTest annotation

Spring Boot provides the @DataJpaTest annotation to test the persistence layer components that will autoconfigure the in-memory embedded database for testing purposes.

5. JPA and Hibernate Annotations

List of JPA and Hibernate Annotations tutorials

JPA @Id and @GeneratedValue

@Id: Marks a field as the primary key of an entity. @GeneratedValue: Specifies the strategy for generating primary key values.

JPA @Entity and @Table

@Entity: Specifies that a class is an entity and is mapped to a database table. @Table: Specifies the table name associated with an entity.

@Column Annotation

@Column: Specifies the mapping for a database column.

JPA @Transient Annotation

@Transient: Excludes a field from being persisted in the database.

JPA @OneToOne Annotation

@OneToOne: Defines a one-to-one relationship between two entities.

JPA @OneToMany Annotation

@OneToMany: Defines a one-to-many relationship between two entities.

JPA @ManyToOne Annotation

@ManyToOne: Defines a many-to-one relationship between two entities.

JPA @ManyToMany Annotation

@ManyToMany: Defines a many-to-many relationship between two entities.

JPA @JoinTable Annotation

@JoinTable: The @JoinTable annotation in JPA is used to customize the association table that holds the relationships between two entities in a many-to-many relationship.

Hibernate @PrimaryKeyJoinColumn

The @PrimaryKeyJoinColumn annotation in JPA (Java Persistence API) and Hibernate is used in the context of inheritance relationships and table mappings, particularly in the Joined Strategy.

Hibernate @Embeddable and @Embedded

@Embeddable: This annotation is used to declare a class as an Embeddable class. @Embedded: This annotation is used in the entity class to specify a field that will be embedded.

6. Java and Servlet Annotations

List of Servlet Annotations tutorials

@WebServlet Annotation

The @WebServlet annotation is used to define a Servlet component in a web application.

@WebInitParam Annotation

The @WebInitParam annotation is used to specify any initialization parameters that must be passed to the Servlet or the Filter.

@WebListener Annotation

The @WebListener annotation is used to annotate a listener to get events for various operations on the particular web application context.

@WebFilter Annotation

The @WebFilter annotation is used to define a Filter in a web application.

@MultipartConfig Annotation

The @MultipartConfig annotation, when specified on a Servlet, indicates that the request it expects is of type multipart/form-data.

Java @FunctionalInterface

The @FunctionalInterface annotation indicates that an interface is a functional interface and contains exactly one abstract method.

Post a Comment

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

annotation list spring

Javatpoint Logo

  • Spring Boot
  • Interview Q

Spring Boot Tutorial

Creating project, project components, spring boot aop, spring boot database, spring boot view, spring boot misc, spring boot - restful, spring tutorial, spring cloud, spring microservices.

Interview Questions

JavaTpoint

Spring Boot Annotations is a form of metadata that provides data about a program. In other words, annotations are used to provide information about a program. It is not a part of the application that we develop. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.

In this section, we are going to discuss some important that we will use later in this tutorial.

It applies to the setter method. It indicates that the annotated bean must be populated at configuration time with the required property, else it throws an exception .

Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching data-type.

It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions.

It is used when we want to scan a package for beans. It is used with the annotation @Configuration. We can also specify the base packages to scan for Spring Components.

It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be managed by Spring Container.

It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated with is found during the classpath. The Spring Framework pick it up and configure it in the application context as a .

The @Controller is a class-level annotation. It is a specialization of . It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with annotation.

It is also used at class level. It tells the Spring that class contains the .

It is a class-level annotation. The repository is a (Data Access Object) that access the database directly. The repository does all the operations related to the database.

It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. . It is a combination of three annotations and . It is used to map the . It has many optional elements like , and . We use it with the class as well as the method.

It maps the requests on the specific handler method. It is used to create a web service endpoint that It is used instead of using: It maps the requests on the specific handler method. It is used to create a web service endpoint that It is used instead of using: It maps the requests on the specific handler method. It is used to create a web service endpoint that or It is used instead of using: It maps the requests on the specific handler method. It is used to create a web service endpoint that a resource. It is used instead of using: It maps the requests on the specific handler method. It is used instead of using: It is used to HTTP request with an object in a method parameter. Internally it uses to convert the body of the request. When we annotate a method parameter with the Spring framework binds the incoming HTTP request body to that parameter. It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a return an object into JSON and XML format. It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL contains a path variable. We can define multiple @PathVariable in a method. It is used to extract the query parameters form the URL. It is also known as a . It is most suitable for web applications. It can specify default values if the query parameter is not present in the URL. It is used to get the details about the HTTP request headers. We use this annotation as a . The optional elements of the annotation are For each detail in the header, we should specify separate annotations. We can use it multiple time in a method It can be considered as a combination of and annotations The @RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody. It binds a method parameter to request attribute. It provides convenient access to the request attributes from a controller method. With the help of @RequestAttribute annotation, we can access objects that are populated on the server-side. with real-world examples.



Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Boot
  • JSF Tutorials
  • Binary Search Tree Traversal
  • Spring Batch Tutorial
  • AngularJS + Spring MVC
  • Spring Data JPA Tutorial
  • Packaging and Deploying Node.js

Spring Annotations [Quick Reference]

June 19, 2022 //  by  ClientAdministrator

Below is the summary of the spring annotations that people use most frequently across spring applications. Spring Framework 2.5 added the annotations to the framework.

Before that, the XML files defined every configuration. Annotations became more convenient to reduce the XML configuration files and annotate the classes and methods with different annotations used at the time of scanning the files in the classpath .

Quick Reference for Spring Annotations

In this tutorial, I will list down the essential spring annotations used in Spring Core, Spring MVC , Spring Boot , Spring Data JPA , etc. modules previously published in this blog . I will continuously update this reference when I am writing the tutorial for new annotations.

You can bookmark this tutorial for quick reference of the most important annotations used in spring applications.

Spring Annotations Reference

Annotations Description
@ annotation is the generalized form considered as a candidate for auto-detection when using annotation-based configuration and classpath scanning. It extended to more specific forms such as @ , @ , and @ .
The XML files define string bean dependencies, and the same can be automatically detected by the Spring container by using the @ annotation. This would eliminate the use of XML configurations.
There may be scenarios when you create more than one bean of the same type and want to wire only one of them with a property. Control this using @ annotation along with the annotation.
annotation applies to bean property setter methods and enforces required properties
This tutorial explains the difference between these three annotations @ , @ and @ used for injecting the objects.
@ and @ annotations are JSR-330 annotations were introduced in as an alternative for the spring annotations @ and @ .
This tutorial explains the JSR-250 annotations that Spring 2.5 introduces, which include , and annotations.
@ annotation is inherited from the @ annotation. This is the special version of @ annotation for implementing the . @ was added as part of the release.
@ annotation for facilitating us to get the header details easily in our controller class. This annotation would bind the header details with the method arguments, and it can be used inside the methods.
@ annotation used for defining the exception handler with specific exception details for each method. This component will handle any exception thrown on any part of the application.
@ annotation can be used as the method arguments or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to a model object.
This tutorial explains one of the new features introduced in ,
This spring data series tutorial explains @ annotation and how to create a custom query using the @ annotation.
This tutorial explains how to enable profiles in your spring application for different environments.
Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @ annotation. If you annotate a class with @ , it indicates that the class defines the beans using the @ annotation.
We have to use  for accepting the customized or more dynamic parameters in the request paths.
This tutorial explains some of the key annotations that are related to Spring MVC applications @ , @ , @ , @ , and @
This tutorial explains the difference between the two annotations @ and @ .
You can use @ annotation for mapping web requests to particular handler classes or handler methods.
 This tutorial shows how to load the properties file values using the @ annotation.
is the annotation used for consolidating all the configurations defined in various configuration files using annotation.
Use annotation to define a particular method that should be within a transaction.
This is annotation is the heart of spring boot application. @ indicates that it is the entry point for the spring boot application.
This example demonstrates how to use the @ annotations for auto-configuring the spring boot applications.
@ annotation is the annotation-driven cache management feature in the spring framework. This annotation added to the spring in .

I will be adding more tutorials on annotations on this page. The above list will be updated frequently to reflect the latest spring annotations in the framework. If you are interested in receiving the updates on spring framework, please subscribe here .

Thank you for reading my blog!! Happy Learning!! If you have any questions related to spring development, please drop a comment or send me a mail. I will try my best to respond to your queries.

National Skills Registry

SpringHow

Spring Boot Annotations | Beginners guide

' src=

Let’s take a look at a list of important spring boot annotations and when to use them with an example.

What are annotations?

Annotations are a form of hints that a developer can give about their program to the compiler and runtime. Based on these hints, the compilers and runtimes can process these programs differently. That is exactly what happens with annotations in spring boot. Spring Boot uses relies on annotations extensively to define and process bean definitions. Some of the features we discuss here are from Spring Framework. But Spring Boot itself is an opinionated version of Spring.

Spring Boot annotation catagories

Based on the use case, Spring annotations fall in to one the following categories.

  • Bean definition annotations (from Core Spring Framework)
  • Configuration annotations

Spring Component annotations

  • Other modules Specific spring-boot annotations

1. Spring Core Annotations

These annotations are not part of spring boot but the spring framework itself. These annotations deal with defining beans. So, Lets look at each of these in details.

You should use the @Bean on a method that returns a bean object. For example, you could define a bean as shown below.

The @Autowired annotation lets you inject a bean wherever you want(most importantly factory methods like the one we seen above). For example, we needed a MyDto for MyService in our previous example. As we had to hardcode in that example, you can simplify it as shown here.

As you see here, @Autowired annotation makes sure spring boot loads an appropriate MyDto bean. Note that, you would get an error if you haven’t defined a MyDto bean. You could work around this by setting @Autowired(required=false) .

This approach provides you a default approach that you can override later.

You could also use the @Autowired annotation for arbitrary number of beans. This is done by setting the annotation at the method level. For instance, take a look at this snippet.

In the above scenario, all three beans must be defined for the myServiceUsingAutowireMultiple factory method to succeed.

Similar to setting required flag in @Autowired , you should use this annotation to mark a certain field or setter method as required. For instance, take a look at this snippet.

2. Spring Boot Configuration annotations

Spring Boot favors java annotations over xml configurations. Even though both of them have pros and cons, the annotations help create complex configurations that work dynamically. So lets go thorough each of these with some examples.

@SpringBootApplication

The @SpringBootApplication annotation is often used in the main class. This annotation is equivalent to using @Configuration , @EnableAutoConfiguration  and  @ComponentScan together. This annotation is responsible for setting up which autoconfiguration to enable and where to look for spring bean components and configurations.

@Configuration

This annotation is used together with the bean definition annotations. When the @ComponentScan finds a class that is annotated with @Configuration , it will try to process all @Bean and other spring related methods inside it.

Configuration properties

This spring boot specific annotation helps bind properties file entries to a java bean. For example, take a look at these configs.

Let’s map these into a java bean.

If setup correctly, Spring boot will create a AppConfig bean object with values mapped from properties. Subsequently, We can autowire them wherever we want.

@Value annotation

This annotation is similar to @Autowired . Except this one is for accessing properties entries instead of beans.

You could also use @Value to access complex SpEL expressions.

there are other few spring boot annotations for configurations that we would not discuss here.

While @Bean lets you create bean using factory methods, you could simply mark a class with one of the following component annotations. These annotations create a singleton bean of that specific class.

In a way these spring boot annotations provide context to what those beans represent in the system. They are,

@Component annotation

This is the basic version among those four. This annotation on a class makes a singleton bean of that said class. For example, the following creates a bean of type BookService with the name “bookService”.

Once the component scan finds this class, it will try to use the constructor to create a BookService object. As you see here, the constructor needs a Dto bean. So spring boot will look for one that satisfies that requirement.

@Service Spring boot annotation

This annotation is similar to Component in everyway. The only reason to use a @Service annotation instead of @Component is for convention(domain driven design).

@Controller annotation

The @Controller marks a class as a spring web MVC controller. This annotation is usually used along with web based spring applications. Apart from the MVC related features it brings, the rest of the behavior stands in line with @Component .

Once the spring MVC sees a controller class, it looks for all @RequestMapping and configures them to handle requests. We will take a look at these in detail later.

There is also a restful variant of @Controller called @RestController . There is also @GetMapping, @PostMapping and other mapping annotations available part of Spring MVC. They are more specialized versions of @RequestMapping annotations.

@RequestMapping

The request mapping annotation lets spring MVC know which controller class method to call. This annotation takes two parameters called path and method . This way we could map them based on path as well as HTTP methods like , GET, POST, PUT and DETELE.

@ResponseBody

The response body is an optional annotation for controller methods. When supplied, this annotation will convert the method return value in to JSON response.

For example, the above code would return a JSON array of strings.

@Repository annotation in Spring Boot

The repository annotation is a bit different among all other stereotypes annotations. Even though this annotation is used extensively in JPA, this annotation came into picture as part of Domain Driven Design.

A common use case would be to annotate JPA repository interfaces. This way Spring-JPA module can provide JPQL support. For example, We could write a BookDto as shown here.

Even though we don’t need to annotate interfaces that extend, it is still a good convention. Also, apart from being a repository, all behaviours from @Component is applicable for @Repository annotation.

Spring boot Module-specific annotations

As spring boot comes with various modules like JPA, MVC, RabbitMQ, Scheduling, caching etc., all of these modules also provide their own annotations for us to use. We have seen some of the annotations from JPA and MVC. So let’s go through the remaining quickly.

Scheduling related annotations

The @Scheduled annotation helps make a method execute on a specific interval.

This annotation takes one of fixedDelay , fixedRate or quartz compatible cron expression.

Caching annotations

Caching annotations play important role in application performance. The cache abstraction in spring boot is powerful and you should take a look. Here are the important annotations from this module.

The @EnableCaching annotation enables support for caching by auto-configuring a cache manager. Usually this annotation goes on the spring boot’s main class.

@Cacheable annotation marks a method’s return values to be cacheable. This way, when the first time the method was called with a specific parameter, the value is saved in the cache. If another request calls the same method with the same parameter, spring boot will return the value from cache instead of executing the method.

As you can see, it takes a cache name and a key to store the result. This way when a new request comes with the same key, we could get the result from cache instead of running the method again.

The @CacheEvict annotation lets you clear a specific value from the cache. It could also be used to clear the entire cache if needed. This annotation exists because your cached results may be outdated and might need a refresh. For example, if you update an entity in DB, then you might want to clear the cached value as well.

AMQP/RabbitMQ annotations

The AMQP module provides certain annotations to deal with message queues of RabbitMQ. The important annotations are listed here.

The @EnableRabbit adds autoconfiguration for AMQP. This annotation is responsible for enabling RabbitAutoConfiguration . Without this annotation, the remaining AMQP annotations won’t work.

@RabbitListener takes a queue name and executes the annotated method. For example, you could read messages from queues as shown here.

There are also few annotations like @Exchange , @queue and @QueueBinding which are used along with @RabbitListener .

We saw a hand-picked list of important annotations used in spring boot. These annotations solve the problem of defining spring beans, utilize them dynamically and configure them. You can find most of these annotations in the samples available in our Github repository .

  • Spring Cache For Better application performance
  • Spring Boot Redis Cache
  • Handling Lists in Thymeleaf view
  • Constructor dependency injection in Spring Framework

Similar Posts

10 reasons why you should use spring boot..

Spring Boot has earned its place in the Java community for various reason. In this post, We will take a look at 10 Reasons Why You should use Spring Boot. 1) Faster Development Spring Boot makes a lot of decisions and opinionated defaults over Spring Ecosystem. This nature helps the developer to set up and…

Derby Embedded Database for Spring Boot

In this post, We will see how we can use Apache Derby embedded database with Spring Boot applications with an example. Introduction Apache Derby is a pure java implementation of a relational database. Also, it complies with JDBC and RDBMS standards. For this reason, we can easily embed Derby into applications. Derby Dependencies for Spring…

Spring Boot Actuator Info endpoint – Complete Guide

Introduction In this post, we will take a look at the spring boot actuator info endpoint. And also how to customize it to show build info, git commit info and extra info from the environment. Spring Boot Actuator Dependency First, you need to add the dependency for actuator. Once added, you can open the /actuator/info…

Install and Run Spring Boot Linux Service Guide

Let’s learn how to install a spring boot as a Linux service. Requirements You will need, Basics of running a spring boot application Understanding linux services and file system. 15 minutes of your time. Make the jar an executable Spring boot applications can be started using the command java -jar hello-world.jar. We have seen this behavior in the posts How…

Logging In Spring Boot

Spring Boot uses Apache Commons Logging under the hood. However, it lets you choose a logging library of your choice. Let’s take a look at Some of the configurations and best practices while using Spring Boot. Overview By default, if you use the starters, then your application will use Logback for logging. The framework also…

Spring Boot and Zipkin for Distributed Tracing

In this post, We will learn how to use Zipkin with Spring Boot for distributed tracing. Spring Boot is currently the first choice of Developers to create microservices. With multiple services in place, Traceability of a single request can be cumbersome. Here is Zipkin to the rescue. Zipkin Architecture Zipkin is a distributed tracing tool that has…

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

Inject Arrays and Lists From Spring Properties Files

Last updated: May 11, 2024

annotation list spring

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> REST With Spring (new)

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’re going to learn how to inject values into an array or List from a Spring properties file.

2. Default Behavior

We’ll start with a simple application.properties file:

Let’s see how Spring behaves when we set our variable type to String[] :

We can see that Spring correctly assumes our delimiter is a comma and initializes the array accordingly.

We should also note that, by default, injecting an array works correctly only when we have comma-separated values.

3. Injecting Lists

If we try to inject a List  in the same way, we’ll get a surprising result:

Our List contains a single element, which is equal to the value we set in our properties file.

In order to properly inject a List , we need to use a special syntax called Spring Expression Language (SpEL):

We can see that our expression starts with #  instead of the $ that we’re used to with  @Value .

We should also note that we’re invoking a split method, which makes the expression a bit more complex than a usual injection.

If we’d like to keep our expression a bit simpler, we can declare our property in a special format:

Spring will recognize this format, and we’ll be able to inject our List using a somewhat simpler expression:

4. Using Custom Delimiters

Let’s create a similar property, but this time, we’re going to use a different delimiter:

As we’ve seen when injecting List s, we can use a special expression where we can specify our desired delimiter :

5. Injecting Other Types

Let’s take a look at the following properties:

We can see that Spring supports basic types out-of-the-box, so we don’t need to do any special parsing :

This is only supported via SpEL, so we can’t inject an array in the same way.

6. Reading Properties Programmatically

In order to read properties programmatically, we first need to get the instance of our Environment object:

Then we can simply use the getProperty  method to read any property by specifying its key and expected type :

7. Conclusion

In this article, we learned how to easily inject arrays and List s through quick and practical examples.

As always, the code is available over on GitHub .

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

Build your API with SPRING - book cover

Follow the Spring Category

annotation list spring

10 Spring Boot Performance Best Practices

' src=

Spring Framework  is one of the most popular and mature application development frameworks available in the Java ecosystem, and  Spring Boot  simplifies the process of creating Spring-powered applications by providing pre-configured modules, automatic configuration, starter dependencies, and more. This simplicity, popularity, and maturity have caused many systems out there to be implemented with Spring Boot, and it is quite possible that  some of them are not optimized and performant .

In this article, we will first discuss what performance is in general, and then we will discuss 10 Spring Boot Performance Best Practices to make our Spring Boot fast and resource-efficient.

Table of Contents

What do we mean when we say performance.

Traditionally, Performance refers to how effectively an application performs its tasks ( Runtime efficiency ), which we also call  speed , and how efficiently it uses system resources ( Resource efficiency ).

In modern software development, Performance has different aspects that are somehow related to these two (Runtime & Resource efficiency):

  • Scalability : Capability to sustain performance and functionality under higher workloads, user numbers, or data amounts.
  • Reliability:  Capability to be consistent and execute its intended functions without disruptions or errors.
  • Throughput:  Capability to manage data and tasks smoothly for a specific duration.
Typically, the performance of a software application is all about making sure it runs smoothly, quickly, and effectively. It also involves managing resources efficiently and meeting the expectations of users.

How to improve Spring Boot performance?

In the coming sections, we will address ten best practices that will help us to have a performant Spring Boot application. These are not listed in any particular order, and some of them might be applicable to the newer version of Spring Boot.

1- Using the latest version of Spring Boot as much as possible

In every version of Spring Framework and Spring Boot, besides introducing new features and functionalities, there are also several improvements in performance by optimizing the Spring core container and modules, fixing bugs, and more. So, it is highly recommended that you use as many of the latest versions of Spring Boot as possible.

2- JVM version and tuning

Similar to Spring Boot, every  Java LTS release  has a lot of performance improvements. Sometimes, to leverage the performance improvements in the latest version of Spring Boot, we need to use the latest version of Java.

Although the latest version of JVM will improve the performance of your Spring Boot application, JVM tuning can further improve the performance of our Spring Boot application. JVM tuning is out of the scope of this article, but I can mention some areas that we need to pay attention to:

  • Initial and maximum heap size using  -Xms  and  -Xmx
  • Other JVM memory settings
  • Choose the proper  GC  implementation

Optimal JVM and GC settings differ based on your application and environment. Testing various configurations and monitoring performance are essential to identify the best settings.

3- Using Virtual Threads in Web MVC stack on JDK 21

Since version 3.2, Spring Boot has started to support Virtual Threads (Project Loom) in different ways. You can find more information about it in my previous article about this feature: Read more: Here

To use this feature, you need to use JDK 21 or higher,

The most important advantage of Virtual Threads is that they improve the  Scalability  and  Performance  of Spring Boot applications by introducing a lightweight threading model while keeping  backward compatibility  and  decreasing the complexity  of asynchronous programming without sacrificing performance.

We can easily enable Virtual Threads in Spring Boot using this config:

By existing in this config, Spring Boot Web MVC is handling a web request, such as a method in a controller, which will run on a virtual thread.

4- Spring AOT and Spring GraalVM Native Image

GraalVM Native Images offers a new approach to running Java applications with  reduced memory usage  and significantly  faster startup times  compared to the JVM

It is ideal for container-based deployments and Function-as-a-Service platforms, GraalVM Native Images require ahead-of-time processing to create an executable through static code analysis. The result is a platform-specific, standalone executable that doesn’t need a JVM for runtime.

Since GraalVM is not directly aware of dynamic elements of our Java code, such as  reflection ,  resources ,  serialization , and  dynamic proxies , we need to provide some information about those elements for GraalVM. On the other hand, Spring Boot applications are dynamic, with configuration performed at runtime.

Spring AOT  (Ahead-of-Time) processing is a feature provided by the Spring Framework that enables the transformation of Spring applications to make them more compatible with GraalVM.

Spring AOT performs ahead-of-time processing during  build time  and generates additional assets such as Java codes, bytecodes, and GraalVM JSON hint files that help GraalVM for ahead-of-time compilation.

[image for ahead-of-the-time processing and ahead-of-the-time compilation]

To achieve this, we need to use the GraalVM build tools plugin in our Spring Boot project:

Then, to build the GraalVM Native Image, we can run the  spring-boot:build-image  goal with the  native  profile active:

It will create a docker image using Buildpacks for us. If you want to know more about the Cloud Native Buildpacks and how Spring Boot is using it, read this article.

To generate a  native executable  instead of a Docker image, we can run this command (make sure that a GraalVM distribution is installed on your machine):

5- JVM Checkpoint Restore feature (Project CRaC)

This feature was added to Spring Boot from version  3.2  and provided by the JVM to enable a running Java application to  save its state , called a “checkpoint,” and then  restore that state  at a later time. Spring Boot integrated this feature with its  ApplicationContext  lifecycle for the automatic checkpoint, and it can be used simply by adding the – Dspring.context.checkpoint=onRefresh  parameter.

This feature can improve the performance of a Spring Boot application in the following ways:

  • Faster startup times : To enhance performance, the Spring Boot app can be optimized by saving a warmed-up JVM state and skipping time-consuming initialization on restarts.
  • Improved stability : Enhance the Spring Boot app’s stability by restoring the JVM state from a reliable checkpoint and bypassing initialization-related issues for a smoother, more dependable experience.
  • Reduced resource usage : Optimize resource usage for the Spring Boot app by reusing existing JVM resources from checkpoints and reducing overall resource consumption.

To use this feature, we need to install a  CRaC-enabled  version of the JDK and use Spring Boot 3.2 or later.

To know more about this feature, you can read our previous deep article about this feature: read more: Here

6- Class Data Sharing (CDS)

Class Data Sharing (CDS) is a feature of the Java Virtual Machine (JVM) that can help decrease Java applications’  startup time  and  memory footprint . Starting in version 3.3, it was integrated into Spring Boot.

The CDS feature comprises two main steps:  1— Creating the CDS Archive, which creates an archive file (with  .jsa  format) containing the application classes when the application exits  2— Using the CDS Archive, which loads the  .jsa  file into memory.

CDS reduces the Spring Boot application startup time because accessing the shared archive is faster than loading the classes when the JVM starts. It is also a memory-efficient solution because:

A portion of the shared archive on the same host is mapped as read-only and shared among multiple JVM processes, and also the shared archive contains class data in the form that the Java Hotspot VM uses it.

7- Configuring threads for Spring MVC and Database centric app

Spring Boot application can handle multiple requests in parallel, and the key factor to achieve high throughput is to have enough thread to handle requests. Two important layers that can cause bottlenecks and need to be configured carefully are the Controller and Database access layers.

🌐 Controller layer threads configuration:

If you cannot use the Virtual Thread feature in your Spring MVC application for any reason, it is very important to properly configure the  thread pool  for the controller layer.

Since Spring MVC applications run on  servlet containers  like Tomcat, Jetty, or Undertow, we need to know specific configuration keys for our servlet containers to configure the thread pool. For example, in the case of Tomcat, we have two important keys for thread configuration:

  • server.tomcat.threads.max : Maximum number of worker threads for request processing.
  • server.tomcat.threads.min-spare : The minimum number of worker threads kept alive, which is also equal to how many threads are created at startup time.

Depending on the servlet container you are using, there are more configurations that can help us configure it for better performance. For example, for Tomcat, there are two timeout-related configs (server.tomcat.connection-timeout and server.tomcat.keep-alive-timeout) that might need to be adjusted to improve performance.

🗄️ Database access layer threads configuration:

Since JDBC is a connection-oriented standard for communicating with a database, it is very important to use a  connection pool . By default, Spring Boot uses  HikariCP  as the connection pool. Similar to servlet containers, each connection pool library has its own configuration key to configure it, for HikariCP the most important config for the connection pool are:

  • spring.datasource.hikari.maximum-pool-size : Maximum number of database connections in the pool.
  • spring.datasource.hikari.minimum-idle : Minimum number of idle database connections in the pool.

8- Use caching strategies

Choosing a proper caching strategy for our Spring Boot application can greatly improve its performance. These days, we have many microservices with data spread between them. By leveraging a proper caching strategy, we can improve performance and cut several round trips.

Based on the application’s scale, data access patterns, and performance requirements, we need to decide about two important aspects of caching:

1- What do we cache?  What piece of information in our application do we want to keep in the cache?

2- How do we cache?  What mechanism or approach of caching do we use? Do we want to use local cache, distributed cache, or both? For how long do we want to keep a piece of data in the cache?

Fortunately, Spring Boot provides a set of useful libraries to help us with caching. We have a dedicated article about caching strategies in Spring Boot. You can read it: Here .

9- Adopting resiliency patterns and best practices

I believe that this is a very important topic, especially these days, because of the increasing number of applications based on the microservices architecture.

Following resiliency patterns such as  Circuit Breaker ,  Timeouts, Fallback, and Retries  helps Spring Boot applications better handle failures, allocate resources efficiently, and provide consistent performance, ultimately leading to an improved overall application performance.

Spring Boot supports resiliency patterns through several built-in features and integrations with popular libraries like  Resilience4j . Spring Boot simplifies the integration of Resilience4j by  auto-configuring  the required beans and providing a convenient way to configure resilience patterns through properties or  annotations .

Spring Cloud Circuit Breaker  provides an abstraction layer for circuit breakers, and Resilience4j can be configured to be used under the hood.

10- Monitoring and Profiling

By combining monitoring and profiling, you can gain a deep understanding of your Spring Boot application’s performance and make data-driven decisions to improve it. In our last article, we went deep into Static and Dynamic code analysis and its relation with finding performance problems using Monitoring and Profiling: Read more: Here.

Spring Boot, out of the Box, has many libraries and tools for this purpose.  Spring Boot Actuator  can monitor application health, gather metrics, and identify performance bottlenecks. On the other hand, from Spring Boot 3.x, there is very good integration with  Micrometer  using Spring autoconfiguration, which helps us have better metrics and distributed tracing, which, lastly, leads to better application monitoring.

How Digma can help to improve Spring Boot app performance

Interestingly, Digma is a tool that allows us to profile and monitor the Spring Boot applications without needing to deploy the application.

Digma can help us find bottlenecks, slow queries, cache misses, and more insight during the development inside the IDE. These features make Digma a hidden weapon in our toolkit to improve the Spring Boot application performance.

Final Thought: 10 Spring Boot Performance Best Practices

In this article, we reviewed ten ways to improve Spring Boot application performance. Some improve  runtime performance , and some optimize the application’s  consumed resources . However, some approaches require using a specific Java and Spring Boot version. Of course, there are other ways to improve Spring programs, especially best practices that can apply at the coding level. I would be happy if you mentioned other best practices in the comment section.

Download Digma: Here

Similar Posts

How to Detect Cache Misses Using Observability

How to Detect Cache Misses Using Observability

Coding Horrors: The Tales of Refactoring and Feature Creep 

Coding Horrors: The Tales of Refactoring and Feature Creep 

' src=

How to Detect and Prevent Anti-Patterns in Software Development

' src=

Identifying Code Concurrency Issues with Continuous Feedback (CF)

' src=

Top Exciting Features Coming in Spring Boot 3.2 (Part2)

How to use traces to avoid breaking changes

How to use traces to avoid breaking changes

' src=

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

© 2024 digma.ai  | For California Residents: Do not sell my personal information | All Rights Reserved

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Spring: how to inject an inline list of strings using @Value annotation [duplicate]

How do I inject a list of string values using the @Value annotation. I'm using Spring 4.1.2.

I've tried:

and then based on the spring el documentation for inline lists :

These attempts only inject a string literal of the value given as the only element in the list.

In this case, I'd like to be able to simply hard-code the values rather than read from a property file. This approach seems a little less smelly than:

In the past, I've used spring's XML configuration to wire up beans, and in that case I could do (assuming the bean had a public setter for the userObjectClasses property):

Is there an analog to this when using annotation based configuration?

Brice Roncace's user avatar

  • The answer hasn't helped yet? If it helped - then you could mark the question as answered. BTW comment below also helps. –  Yuri Commented Jun 15, 2015 at 9:15

list.of.strings=first,second,third took from properties file for e.g.

Then using SpEL :

Then I don't think that you need to use annotation for such type of tasks. You could do all work just like you've menitioned or in the @PostConstruct in order to initialize some fields.

Yuri's user avatar

  • 15 The spring convertion service will perform the split for you if your reference is an array or Collection , so you don't need that ugly expression: just @Value("${list.of.strings}") –  Costi Ciudatu Commented Dec 9, 2014 at 23:34
  • @CostiCiudatu how does it know which delimiter to split on? does this only work for a , ? –  Erin Drummond Commented May 23, 2016 at 21:16
  • 3 @ErinDrummond It uses StringUtils.commaDelimitedListToStringArray internally; so yes, it relies on the comma-separated format. –  Costi Ciudatu Commented May 23, 2016 at 22:32
  • 1 @CostiCiudatu how to enable spring convertion service? not working for me by default. spring4 –  Daniel Hári Commented Feb 1, 2018 at 13:01

Not the answer you're looking for? Browse other questions tagged java spring or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • 11 trees in 6 rows with 4 trees in each row
  • How to manage talkover in meetings?
  • What makes Python better suited to quant finance than Matlab / Octave, Julia, R and others?
  • Guessing whether the revealed number is higher
  • Old SF story about someone who detonated an atomic bomb, sacrificing self to save society from an evil government
  • What is the purpose of the BJT in this circuit?
  • How shall I find the device of a phone's storage so that I can mount it in Linux?
  • What spells can I cast while swallowed?
  • In the UK, how do scientists address each other?
  • Don't make noise. OR Don't make a noise
  • What is meant by "I was blue ribbon" and "I broke my blue ribbon"?
  • Read an article about connecting a hot tub to a heat pump, looking for details
  • Were there any stone vessels (including mortars) made in Paleolithic?
  • Is intuitionistic mathematics situated in time?
  • 为什么字形不同的两个字「骨」的编码相同(从而是一个字)?
  • Siunitx: spread table content accross page
  • Gradual light transition
  • Is "able to find related code by searching keyword 'MyClass '(variable declaration)" a reason to avoid using auto in c++?
  • Why does independent research from people without formal academic qualifications generally turn out to be a complete waste of time?
  • Why was this a draw?
  • Converting cif file with powdll, plotting cif file in excel
  • Do thermodynamic cycles occur only in human-made machines?
  • Reduce the column padding in tabular environment
  • Pregnancy in a hibernated state

annotation list spring

使用Spring Boot实现在线图书管理系统

作者头像

在线图书管理系统在图书馆、书店和教育机构中广泛应用,帮助用户方便地管理图书信息,进行图书的借阅和归还操作。Spring Boot通过其简便的配置和强大的功能支持,使得开发一个在线图书管理系统变得更加容易。本文将详细探讨如何使用Spring Boot实现一个在线图书管理系统,并提供具体的代码示例和应用案例。

第一章 Spring Boot概述

  • 1.1 什么是Spring Boot

Spring Boot是基于Spring框架的一个开源项目,旨在通过简化配置和快速开发,帮助开发者构建独立、生产级的Spring应用。Spring Boot通过自动化配置、内嵌服务器和多样化的配置方式,使得开发者能够更加专注于业务逻辑,而不需要花费大量时间在繁琐的配置上。

  • 1.2 Spring Boot的主要特性
  • 自动化配置 :通过自动化配置减少了大量的手动配置工作,开发者只需定义少量的配置,即可启动一个完整的Spring应用。
  • 内嵌服务器 :提供内嵌的Tomcat、Jetty和Undertow服务器,方便开发者在开发和测试阶段快速启动和运行应用。
  • 独立运行 :应用可以打包成一个可执行的JAR文件,包含所有依赖项,可以独立运行,不需要外部的应用服务器。
  • 生产级功能 :提供了监控、度量、健康检查等生产级功能,方便开发者管理和监控应用的运行状态。
  • 多样化的配置 :支持多种配置方式,包括YAML、Properties文件和环境变量,满足不同开发和部署环境的需求。

使用Spring Initializr生成一个Spring Boot项目,并添加所需依赖。

  • 3.1 创建用户实体类

定义用户实体类,并配置JPA注解。

  • 3.2 创建用户Repository接口

创建一个JPA Repository接口,用于数据访问操作。

  • 3.3 实现用户Service类

创建一个Service类,封装业务逻辑和数据访问操作。

  • 3.4 创建用户Controller类

创建一个Controller类,定义RESTful API的端点,并通过Service类处理请求。

  • 4.1 创建图书实体类

定义图书实体类,并配置JPA注解。

  • 4.2 创建图书Repository接口
  • 4.3 实现图书Service类
  • 4.4 创建图书Controller类
  • 5.1 创建借阅实体类

定义借阅实体类,并配置JPA注解。

  • 5.2 创建借阅Repository接口
  • 5.3 实现借阅Service类
  • 5.4 创建借阅Controller类
  • 6.1 部署Spring Boot应用

Spring Boot应用可以通过多种方式进行部署,包括打包成JAR文件、Docker容器等。

  • 6.2 使用Docker部署Spring Boot应用

Docker是一个开源的容器化平台,可以帮助开发者将Spring Boot应用打包成容器镜像,并在任何环境中运行。

  • 6.3 监控Spring Boot应用

Spring Boot Actuator提供了丰富的监控功能,通过Prometheus和Grafana,可以实现对Spring Boot应用的监控和可视化。

通过Spring Boot,开发者可以高效地构建一个在线图书管理系统,涵盖用户管理、图书管理、借阅管理等关键功能。本文详细介绍了系统的基础知识、Spring Boot的核心功能、具体实现以及部署和监控,帮助读者深入理解和掌握Spring Boot在在线图书管理系统开发中的应用。希望本文能够为您进一步探索和应用Spring Boot提供有价值的参考。

本文分享自 作者个人站点/博客   前往查看

如有侵权,请联系 [email protected] 删除。

本文参与  腾讯云自媒体同步曝光计划   ,欢迎热爱写作的你一起参与!

扫码关注腾讯云开发者

Copyright © 2013 - 2024 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有 

深圳市腾讯计算机系统有限公司 ICP备案/许可证号: 粤B2-20090059  深公网安备号 44030502008569

腾讯云计算(北京)有限责任公司 京ICP证150476号 |   京ICP备11018762号 | 京公网安备号11010802020287

Copyright © 2013 - 2024 Tencent Cloud.

All Rights Reserved. 腾讯云 版权所有

IMAGES

  1. Spring Boot Annotations: Learn Spring Boot by Annotations

    annotation list spring

  2. Spring Boot And Spring Framework Annotations Cheat Sh

    annotation list spring

  3. GitHub

    annotation list spring

  4. Spring Boot Annotations

    annotation list spring

  5. Spring annotation

    annotation list spring

  6. Spring Framework Annotations Cheat Sheet

    annotation list spring

VIDEO

  1. Annotations no Spring o que são e para que servem?

  2. 25-Custom validation annotation in spring MVC |Spring MVC

  3. 24. @Qualifier Annotation in Spring

  4. Spring MVC annotation configuration in 8 minutes

  5. 03-3 Spring Boot Application Annotation

  6. Spring Framework Tutorial: Required Annotation

COMMENTS

  1. Spring Annotations List (with Examples)

    The @Bean is a method-level annotation used to declare a spring bean. When the container executes the annotated method, it registers the return value as a bean within a BeanFactory. By default, the bean name will be the same as the method name. To customize the bean name, use its' name ' or ' value ' attribute. 2.2.

  2. Spring Core Annotations

    Spring Core Annotations. 1. Overview. We can leverage the capabilities of Spring DI engine using the annotations in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages. We often call these "Spring core annotations" and we'll review them in this tutorial. 2.

  3. Spring Framework Annotations

    The Java Programming language provided support for Annotations from Java 5.0. Leading Java frameworks were quick to adopt annotations and the Spring Framework started using annotations from the release 2.5. Due to the way they are defined, annotations provide a lot of context in their declaration. Prior to annotations, the behavior of the Spring Framework

  4. Spring Framework Annotations

    Spring Framework Annotations. Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects.

  5. Spring Boot Annotations List

    It provides defaults for code and annotation configuration to quick start new Spring projects within no time. Let's list all the annotations from these packages. 1. @SpringBootApplication. @SpringBootApplication annotation indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component ...

  6. PDF Spring Boot Annotations: Top 30+ most Used Spring Annotations

    frameworks quickly adopt the annotation's concept. Spring Boot has provided the support for the annotations since the release of Spring 2.5. Due to their extensive structure and internal concepts, the annotations provide a lot of context in their declaration. Before the annotations, the Spring Boot project's behavior was controlled and

  7. Spring Boot Annotations

    It means that Spring Boot looks for auto-configuration beans on its classpath and automatically applies them. Note, that we have to use this annotation with @Configuration: 4. Auto-Configuration Conditions. Usually, when we write our custom auto-configurations, we want Spring to use them conditionally.

  8. List of All Spring Boot Annotations, Uses with examples

    Here's an extensive list of Spring Boot annotations 1. Core Annotations: a). @SpringBootApplication . The @SpringBootApplication annotation is used to mark the main class of a Spring Boot application. This is the Spring Boot Application starting point. It combines three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan ...

  9. Spring Annotations Cheat Sheet

    Here are the most important annotations any Java developer working with Spring should know: @Configuration - used to mark a class as a source of the bean definitions. Beans are the components of the system that you want to wire together. A method marked with the @Bean annotation is a bean producer. Spring will handle the life cycle of the beans ...

  10. Annotations :: Spring Framework

    This section covers annotations that you can use when you test Spring applications. Section Summary. Standard Annotation Support; Spring Testing Annotations; Spring JUnit 4 Testing Annotations; Spring JUnit Jupiter Testing Annotations; Meta-Annotation Support for Testing; Appendix Standard Annotation Support. Spring Framework. 6.2.0-SNAPSHOT

  11. Spring Web Annotations

    1. Overview. In this tutorial, we'll explore Spring Web annotations from the org.springframework.web.bind.annotation package. 2. @RequestMapping. Simply put, @RequestMapping marks request handler methods inside @Controller classes; it can be configured using: path, or its aliases, name, and value: which URL the method is mapped to.

  12. The Essential List of Spring Boot Annotations and Their Use Cases

    Below are all the essential spring boot annotations you should know about. 1. @Bean. The "@Bean" is a method-level annotation that is analogous to XML <bean> tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory.

  13. Java, Java EE, Spring and Spring Boot Annotations with Examples

    The @WebMvcTest annotation is used to perform unit tests on Spring MVC controllers. It allows you to test the behavior of controllers, request mappings, and HTTP responses in a controlled and isolated environment. 4. Spring Data JPA Annotations. List of 4.

  14. Spring Boot Annotations

    Spring Boot Annotations @EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication. @SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration ...

  15. java

    I want to have a list of values in a .properties file, i.e.: my.list.of.strings=ABC,CDE,EFG And to load it in my class directly, i.e.: @Value("${my.list.of.strings}") private List<String> myList; As I understand, an alternative of doing this is to have it in the Spring config file, and load it as a bean reference (correct me if I'm wrong), i.e.

  16. Spring Annotations [Quick Reference]

    This tutorial explains the JSR-250 annotations that Spring 2.5 introduces, which include @Resource, @PostConstruct, and @PreDestroy annotations. @RestController. @ RestController annotation is inherited from the @ Controller annotation. This is the special version of @ Controller annotation for implementing the RESTful Web Services.

  17. Validating Lists in a Spring Controller

    In this tutorial, we'll go over ways to validate a List of objects as a parameter to a Spring controller. We'll add validation in the controller layer to ensure that the user-specified data satisfies the specified conditions. 2. Adding Constraints to Fields. For our example, we'll use a simple Spring controller that manages a database of ...

  18. Spring Boot Annotations

    This spring boot specific annotation helps bind properties file entries to a java bean. For example, take a look at these configs. app.maxOrderPriceLimit= 1000. app.payment.enabled= true. app.payment.types=card,cash Code language: Java (java) Let's map these into a java bean.

  19. Inject Arrays & Lists from Spring Property Files

    In this quick tutorial, we're going to learn how to inject values into an array or List from a Spring properties file. 2. Default Behavior. We'll start with a simple application.properties file: arrayOfStrings=Baeldung,dot,com. Let's see how Spring behaves when we set our variable type to String []:

  20. 10 Spring Boot Performance Best Practices

    Spring Boot simplifies the integration of Resilience4j by auto-configuring the required beans and providing a convenient way to configure resilience patterns through properties or annotations. Spring Cloud Circuit Breaker provides an abstraction layer for circuit breakers, and Resilience4j can be configured to be used under the hood.

  21. Spring: how to inject an inline list of strings using @Value annotation

    and then based on the spring el documentation for inline lists: @Value(value = "{top, person, organizationalPerson, user}") private List<String> userObjectClasses. These attempts only inject a string literal of the value given as the only element in the list. EDIT. In this case, I'd like to be able to simply hard-code the values rather than ...

  22. 使用Spring Boot实现在线图书管理系统-腾讯云开发者社区-腾讯云

    在线图书管理系统在图书馆、书店和教育机构中广泛应用,帮助用户方便地管理图书信息,进行图书的借阅和归还操作。Spring Boot通过其简便的配置和强大的功能支持,使得开发一个在线图书管理系统变得更加容易。本文将详细探讨如何使用Spring Boot实现一个在线图书管理系统,并提供具体的代码 ...