Spring Boot Annotations

Spring Boot provides powerful annotations to simplify development. Here’s a categorized list with explanations and examples.

@SpringBootApplication

Marks the main class of a Spring Boot application.


Internally includes:

  • @Configuration – Marks a configuration class
  • @EnableAutoConfiguration – Enables auto-configuration
  • @ComponentScan – Scans for Spring components


@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

@Controller (Web Layer - MVC)

@Controller is a Spring MVC annotation that marks a class as a web controller handling HTTP requests.

Best Use Case: Use @Controller for handling MVC views (Thymeleaf, JSP, etc.).

@Controller
public class MyController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello from @Controller!");
return "hello"; // Returns a view (e.g., hello.html)
}
}

@RestController

A combination of @Controller + @ResponseBody, used for REST APIs.

@RestController
public class MyRestController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}

Difference between @Controller and @RestController:

  • @Controller is used for MVC-based web applications (returns views).
  • @RestController is used for RESTful APIs (returns JSON/XML responses).

@Service (Business Logic Layer)

@Service is a specialized version of @Component, specifically for service-layer logic. It indicates that a class contains business logic.

Best Use Case: Use @Service for business logic or service classes that interact with repositories.

@Service
public class UserService {
public String getUserInfo() {
return "User Information";
}
}

@Entity, @Table, @Column

Used for Hibernate/JPA entity mapping.

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "username", nullable = false)
private String username;
}

@Repository (Data Access Layer)

@Repository is a specialized @Component used for database access logic.

It is mainly used with Spring Data JPA and Hibernate.

Best Use Case: Use @Repository for DAO (Data Access Object) classes that interact with the database.

  • Converts JPA exceptions into Spring DataAccessException.
  • Works seamlessly with Spring Data JPA.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}

@RequestMapping

  • A general-purpose annotation used to map HTTP requests to specific methods.
  • Can handle all HTTP methods (GET, POST, PUT, DELETE, etc.).
  • Supports attributes like path, method, produces, and consumes.
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api") // Base URL for all endpoints
public class UserController {

@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
return "List of users";
}
}

🔹 Alternative: Instead of @RequestMapping(method = RequestMethod.GET), you can use @GetMapping, which is more specific.


@GetMapping

  • Specifically used for handling GET requests.
  • Used for retrieving data from the server.
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api") // Base URL for all endpoints
public class UserController {
@GetMapping("/users")
public String getAllUsers() {
return "List of all users";
}
}

@PostMapping

  • Used to handle POST requests.
  • Typically used for creating new resources.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api") // Base URL for all endpoints
public class UserController {
@PostMapping("/users")
public String createUser() {
return "User created successfully!";
}
}

✔ Can also accept request body using @RequestBody

@PostMapping("/users")
public String createUser(@RequestBody User user) {
return "User " + user.getName() + " created!";
}

@PutMapping

  • Used for updating an existing resource.
  • Handles PUT requests.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api") // Base URL for all endpoints
public class UserController {
@PutMapping("/users/{id}")
public String updateUser(@PathVariable int id, @RequestBody User user) {
return "User with ID " + id + " updated!";
}
}

@DeleteMapping

  • Used to delete a resource.
  • Handles DELETE requests.
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api") // Base URL for all endpoints
public class UserController {
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable int id) {
return "User with ID " + id + " deleted!";
}
}

@PathVariable & @RequestParam

Extracts values from the URL path or query parameters.

@GetMapping("/user/{id}")
public String getUser(@PathVariable int id) {
return "User ID: " + id;
}

@GetMapping("/search")
public String search(@RequestParam String keyword) {
return "Searching for: " + keyword;
}

@Valid & @Validated

Used for validating request body data.

@PostMapping("/register")
public ResponseEntity<String> registerUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User registered!");
}

@Autowired

Injects a dependency automatically.

@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}

@Qualifier

Used when multiple beans of the same type exist.

@Autowired
@Qualifier("beanName")
private MyService myService;

@Primary

Marks a bean as the default when multiple beans of the same type exist.

@Primary
@Bean
public MyService defaultService() {
return new MyService();
}

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.