This content originally appeared on DEV Community and was authored by Dhanush K
Annotations help you write cleaner, more concise code by eliminating the need for explicit configuration in XML files.
Spring Boot annotations can be used to define the behavior of classes, methods, and fields within an application. These annotations provide a wide range of functionality, including dependency injection, web application configuration, data access, and more.
By using these annotations, developers can quickly set up and configure their applications, reducing the amount of boilerplate code and making the development process more efficient.
Some frequently used annotations with explanations:
@SpringBootApplication
- It is a class-level annotation. It is used to mark the main configuration class of a Spring Boot application. It is a meta-annotation.
- This annotation combines three other annotations:
@Configuration
,@EnableAutoConfiguration
, and@ComponentScan
.
-
@Configuration
: Indicates that the class is a source of bean definitions for the application context. -
@EnableAutoConfiguration
: Enables Spring Boot's auto-configuration mechanism, which automatically configures the Spring application based on dependencies present in the classpath. -
@ComponentScan
: Tells Spring to scan the specified package and its sub-packages for components to register in the application context.
@Component
- It is a class-level annotation used to indicate that a class is a Spring component.
- It will automatically detect and register that class as a Spring bean in the application context.
- This allows you to take advantage of Spring's dependency injection capabilities and easily manage the lifecycle of the bean.
- It is a generic stereotype annotation in Spring that serves as a parent for more specific stereotype annotations like
@Service
,@Repository
, and@Controller
. - By using @Component, you are essentially declaring a class as a Spring-managed component without specifying a more specific stereotype.
@Autowired
- It is used in Fields, Constructors and method-level to inject dependencies automatically.
- It helps in achieving loose coupling between components by allowing Spring to manage the dependencies between beans.
- It simplifies the process of wiring beans together and reduces the need for manual configuration.
@Scope("Singleton")
- It is a class-level annotation, to define a bean as a singleton scoped bean.
- By default, Spring beans are singletons if no scope is defined, meaning that only one instance of the bean is created and shared across the application context.
@Scope("Prototype")
- It is a class-level annotation. It is used to define a bean as a prototype scoped bean.
- This means that a new instance of the bean will be created every time it is injected or retrieved from the Spring container.
@Primary
- It is a method-level annotation.
- It used to indicate a primary bean when multiple beans of the same type are present in the Spring application context.
@Qualifier
- It is a method-level annotation.
- When multiple beans of same type are defined in the Spring application context, the
@Qualifier
annotation is used to specify which bean to be injected into a particular dependency. -
@Qualifier
helps resolve ambiguity when auto-wiring by name is not sufficient to uniquely identify the bean to be injected.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@Component
public class Buy {
private Shop shop;
@Autowired
//public Buy(Shop shop){
public Buy(@Qualifier("vegPizza") Shop shop){
this.shop = shop;
}
public void buying() {
shop.getPizza();
}
}
// Other methods in the service class
}
@Configuration
- It is a class-level annotation.
- It is used to indicate that a class declares one or more
@Bean
methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime. - Classes annotated with
@Configuration
can define methods annotated with@Bean
to create and configure beans. These beans are managed by the Spring container and can be injected into other components. -
@Configuration
promotes modularity and encapsulation by allowing you to group related bean definitions and configurations within a single class.
@Bean
- It is a method-level annotation.
- By annotating a method with
@Bean
, you are explicitly declaring that the return value of that method should be managed by the Spring container as a bean. -
@Bean
gives you more control over the instantiation and configuration of beans compared to component scanning or annotations like@Component
- Beans defined using
@Bean
can be injected into other Spring components using dependency injection by auto-wiring it. -
@Bean
is often used when integrating with external libraries or frameworks that require Spring beans to be created in a specific way.
@Configuration %% USED WITH CONFIGURATION %%
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
@Bean
public MyRepository myRepository() {
return new MyRepository();
}
}
@Controller
- It is a class level annotation.
- This annotation marks the class as a Spring MVC controller, which means it can handle incoming HTTP requests.
- It is used to map the data or model object to view or template and show it to the client.
- We can use
@ResponseBody
annotation on individual methods to directly return data (e.g., JSON or XML) instead of a view.
@RestController
- It is a specialized version of the
@Controller
annotation. It is known as Stereotype annotation. - When a method in a class annotated with
@RestController
returns an object, Spring automatically converts that object into JSON or XML response using message converters. - This eliminates the need for an additional
@ResponseBody
annotation on each method. -
@RestController
is a convenience annotation that combines@Controller
and@ResponseBody
, making it easier to write RESTful web services in Spring MVC.
@RequestMapping
- It can be used with both method level and class level of Controller class.
- When annotated with method, it automatically maps the
/Endpoint
toAnyMethod()
method defined under it. - When annotated with class, it acts as a common Pre-End-Point for the methods with
/Endpoints
. -
Eg:
/api/hello
, where@RequestMapping("/api")
,/api
is annotated with class level.
@RestController
@RequestMapping("/api") %% CLASS LEVEL %%
public class ApiController {
@RequestMapping(value="/hello", method=RequestMethod.GET) %% METHOD LEVEL %%
@ResponseBody
public String sayHello() {
return "Hello from API!";
}
@ResponseBody
- It is a method-level annotation.
- When annotated with a method, it indicates that the return value of the method should be written directly to the HTTP response body.
- It converts the object into JSON/XML and return data in JSON or XML formats.
@Service
- It is a class-level annotation.
- It is used to mark a Java class as a service layer component in the Spring application context.
- By using the
@Service
annotation, you can clearly separate the service layer logic from the other layers of your application, such as the controller and repository layers, promoting a clean and maintainable architecture.
@Repository
- It is a class-level annotation.
- @Repository: Marks a class as a data access object (DAO) that interacts with a database.
- It is a special type of DAO (Data Access Object) that provides an abstraction layer between the application and the data source.
@GetMapping
- It is a method-level annotation.
- It is used to map HTTP GET (retrieve) requests to specific handler methods in a controller class.
- It is used to define the URL mapping for a specific controller method.
- It is a specialized version of the
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
@GetMapping("/users") %% NO NEED method=RequestMethod.GET %%
public String listUsers(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users);
return "users";
}
}
@PostMapping
- It is a method-level annotation.
- It is used to map HTTP POST requests to specific handler methods in a controller class.
- It is a specialized version of the @RequestMapping annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User newUser) {
// Create the user in the service layer
User savedUser = userService.createUser(newUser);
return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
}
}
@putMapping
- It is a method-level annotation.
- It is used to map HTTP PUT (update) requests to specific handler methods in a controller class.
- It is a specialized version of the
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
@PutMapping("/users/{userId}")
public ResponseEntity<User> updateUser(@PathVariable("userId") Long userId, @RequestBody User updatedUser) {
// Update the user in the service layer
User savedUser = userService.updateUser(userId, updatedUser);
return ResponseEntity.ok(savedUser);
}
}
@DeleteMapping
- It is a method-level annotation.
- It is used to map HTTP DELETE requests to specific handler methods in a controller class.
- It is used to define the URL mapping for a specific controller method that handles HTTP DELETE requests.
- It is a specialized version of the
@RequestMapping
annotation, which is used to map HTTP requests to controller methods.
@Controller
public class UserController {
@DeleteMapping("/users/{userId}")
public ResponseEntity<Void> deleteUser(@PathVariable("userId") Long userId) {
// Delete the user in the service layer
userService.deleteUser(userId);
return ResponseEntity.noContent().build();
}
}
@PathVariable
- It is a method-parameter-level annotation. (used in method signature-before parameters)
- It used to bind a method parameter to a URI template variable.
- It is used to extract values from the URL path and use them in your controller method.
@GetMapping("/users/{userId}")
public User getUser(@PathVariable("userId") Long userId) {
// Use the userId to fetch the user from the database
return userService.getUserById(userId);
}
@RequestParam
- It is a method-level annotation.
- It used to bind a method parameter to a request parameter.
- It is used to extract values from the query string (the part of the URL after the ?) and use them in your controller method.
@GetMapping("/users")
public List<User> getUsers(@RequestParam("name") String name, @RequestParam("age") int age) {
// Use the name and age parameters to fetch the users from the database
return userService.getUsersByNameAndAge(name, age);
}
@Query
- It is a method-level annotation.
- It is used to define custom queries for repository methods.
- It is used to execute a custom SQL or JPQL (Java Persistence Query Language) query in your repository methods, instead of relying on the default query generation provided by Spring Data JPA.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = :email")
User findByEmail(@Param("email") String email);
}
@Param
- It is a method parameter-level annotation.
- It is used in conjunction with the
@Query
annotation to bind method parameters to query parameters. - This is particularly useful when you have dynamic query parameters that need to be passed to the query.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = :email AND u.name = :name")
User findByEmailAndName(@Param("email") String email, @Param("name") String name);
}
@OneToOne
- It is field/property level annotation.
- It is used to define a one-to-one relationship between two entity classes.
As the Spring framework continues to evolve, the use of annotations in Spring Boot is likely to become even more prevalent, making it an essential skill for any Java developer working with enterprise-level applications.
This content originally appeared on DEV Community and was authored by Dhanush K
Dhanush K | Sciencx (2024-10-28T01:12:04+00:00) Spring Boot Annotations. Retrieved from https://www.scien.cx/2024/10/28/spring-boot-annotations/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.