Detailed Explanation of Spring Boot Common Annotations


Spring Boot is a very popular Java web framework that provides a large number of annotations to simplify development. This article will explain in detail the commonly used annotations in Spring Boot to help you better understand and use Spring Boot.

@SpringBootApplication

@SpringBootApplication is a combined annotation that includes @Configuration, @EnableAutoConfiguration and @ComponentScan. Used to mark a Spring Boot main class. It will automatically scan the components under the package where the main class is located and its subpackages.

@Controller

@Controller is an annotation in Spring MVC used to mark a class as a web controller. When the request arrives, Spring MVC will find the corresponding method through the annotation for processing. In Spring Boot, it is used together with @RestController to build RESTful API.

@RequestMapping

@RequestMapping is used to map HTTP requests to corresponding methods. Can be used on classes or methods. For example:

@Controller
@RequestMapping("/hello")
public class HelloController {
    
    
    @GetMapping
    public String hello() {
    
    
        return "Hello, World!";
    }
}

Here the class is marked with @RequestMapping, indicating that all methods under this class are prefixed with /hello. Mark the method with @GetMapping to indicate that the method only accepts GET requests.

@RestController

@RestController is an annotation in Spring MVC, which is a combination of @Controller and @ResponseBody. In Spring Boot, it is often used to build RESTful APIs.

@RestController
@RequestMapping("/api")
public class ApiController {
    
    
    @GetMapping("/hello")
    public String hello() {
    
    
        return "Hello, World!";
    }
}

Here the class is marked with @RestController, indicating that the class is a RESTful API controller. Mark the method with @GetMapping to indicate that the method only accepts GET requests. The return value will be automatically converted to JSON format.

@Autowired

@Autowired is used to automatically inject dependencies. Can be used on constructors, properties and methods. For example:

@Service
public class HelloService {
    
    
    private final HelloRepository repository;
    
    public HelloService(@Autowired HelloRepository repository) {
    
    
        this.repository = repository;
    }
    
    public String hello() {
    
    
        return repository.getHello();
    }
}

Here the constructor is marked with @Autowired, indicating that HelloRepository will be automatically injected into HelloService.

@Component

@Component is one of Spring's core annotations, used to mark a class as a Spring component. The marked classes will be automatically scanned by Spring and brought into the Spring container management.

@Configuration

@Configuration is used to mark a class as a Spring configuration class. Configuration classes can contain methods annotated with @Bean for configuring Spring Beans.

@Configuration
public class AppConfig {
    
    
    @Bean
    public HelloService helloService() {
    
    
        return new HelloService(helloRepository());
    }
    
    @Bean
    public HelloRepository helloRepository() {
    
    
        return new HelloRepositoryImpl();
}

The class is marked with @Configuration here, indicating that the class is a Spring configuration class. Mark the method with @Bean to indicate that the object returned by the method is a Spring Bean.

@EnableAutoConfiguration

@EnableAutoConfiguration is used to enable the automatic configuration function of Spring Boot. It will automatically configure the corresponding components according to the different project dependencies. Usually, you only need to add this annotation on the main class.

@GetMapping/@PostMapping/@PutMapping/@DeleteMapping

@GetMapping, @PostMapping, @PutMapping and @DeleteMapping are used to mark HTTP requests corresponding to GET, POST, PUT and DELETE respectively. For example:

@RestController
@RequestMapping("/api")
public class ApiController {
    
    
    @GetMapping("/hello")
    public String hello() {
    
    
        return "Hello, World!";
    }
    
    @PostMapping("/hello")
    public String postHello() {
    
    
        return "Hello, POST!";
    }
    
    @PutMapping("/hello")
    public String putHello() {
    
    
        return "Hello, PUT!";
    }
    
    @DeleteMapping("/hello")
    public String deleteHello() {
    
    
        return "Hello, DELETE!";
    }
}

Here, four methods are marked with @GetMapping, @PostMapping, @PutMapping and @DeleteMapping respectively, indicating that they correspond to GET, POST, PUT and DELETE requests respectively.

@PathVariable

@PathVariable is used to get parameters in URL path. For example:

@RestController
@RequestMapping("/api")
public class ApiController {
    
    
    @GetMapping("/{name}")
    public String hello(@PathVariable String name) {
    
    
        return "Hello, " + name + "!";
    }
}

Here the method is marked with @GetMapping, indicating that the method only accepts GET requests. Mark a parameter with @PathVariable to indicate that the parameter is taken from the URL path.

@RequestParam

@RequestParam is used to get the parameters in the HTTP request. For example:

@RestController
@RequestMapping("/api")
public class ApiController {
    
    
    @GetMapping("/hello")
    public String hello(@RequestParam String name) {
    
    
        return "Hello, " + name + "!";
    }
}

Here the method is marked with @GetMapping, indicating that the method only accepts GET requests. Marking a parameter with @RequestParam indicates that the parameter is obtained from the HTTP request.

@ResponseBody

@ResponseBody is used to convert method return value into HTTP response body. Typically used with @Controller or @RestController. For example:

@RestController
@RequestMapping("/api")
public class ApiController {
    
    
    @GetMapping("/hello")
    public String hello() {
    
    
        return "Hello, World!";
    }
}

Here the method is marked with @GetMapping, indicating that the method only accepts GET requests. Marking a method with @ResponseBody indicates that the return value of the method will be returned as the HTTP response body.

@Service

@Service is used to mark a class as a service class. Typically, service classes are used to implement business logic. The marked classes will be automatically scanned by Spring and brought into the Spring container management.

@Transactional

@Transactional is used to mark a method or class as a transactional method or class. If a method or class is marked @Transactional, then the transaction is automatically rolled back when any database operation in that method or class fails.

@Service
public class UserService {
    
    
    @Autowired
    private UserDao userDao;

    @Transactional
    public void addUser(User user) {
    
    
        userDao.addUser(user);
    }
}

Here, the class is marked with @Service to indicate that the class is a service class. Mark a property with @Autowired to indicate that the property needs to be automatically injected. Mark a method with @Transactional to indicate that the method is a transactional method.

@ComponentScan

@ComponentScan is used to automatically scan all components under the specified package and bring them into Spring container management. For example:

@SpringBootApplication
@ComponentScan("com.example.demo")
public class DemoApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
    }
}

Here the main class is marked with @SpringBootApplication, indicating that the class is a Spring Boot application. Mark the main class with @ComponentScan, indicating that all components under the package com.example.demo need to be scanned.

@ConfigurationProperties

@ConfigurationProperties is used to inject property values ​​from configuration files into an object. For example:

@Configuration
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
    
    
    private String name;
    private String version;

    // getters and setters
}

The class is marked with @Configuration here, indicating that the class is a Spring configuration class. Mark the class with @ConfigurationProperties, indicating that the properties prefixed with myconfig in the configuration file need to be injected into the corresponding object of the class.

@Value

@Value is used to inject the property value from the configuration file into a property. For example:

@Service
public class UserService {
    
    
    @Value("${user.age}")
    private int age;
    
    // ...
}

Here, the class is marked with @Service to indicate that the class is a service class. Mark the property with @Value, indicating that the value of the user.age property in the configuration file needs to be injected into the property.

@Conditional

@Conditional is used to enable a component under certain conditions. For example:

@Configuration
@Conditional(MyCondition.class)
public class MyConfig {
    
    
    // ...
}

The class is marked with @Configuration here, indicating that the class is a Spring configuration class. Mark the class with @Conditional to enable the component under the condition of MyCondition.

@Async

@Async is used to mark a method as asynchronous. Asynchronous methods are executed in another thread without blocking the current thread. For example:

@Service
public class UserService {
    
    
    @Async
    public void sendEmail(String email, String content) {
    
    
        // 发送邮件
    }
}

Here, the class is marked with @Service to indicate that the class is a service class. Marking a method with @Async indicates that the method is an asynchronous method.

Guess you like

Origin blog.csdn.net/qq_54351538/article/details/129682009