SoFunction
Updated on 2025-04-06

Summary of common annotations that must be mastered in SpringBoot

Related

@Component: Identify a class as a Spring component (Bean), which can be automatically detected and registered by the Spring container. Common annotations, suitable for components at any level.

@Component
public class MyComponent {
    public void doSomething() {
        ("MyComponent is doing something.");
    }
}

@ComponentScan: Automatically scan Spring components in specified packages and their subpackages.

@ComponentScan("") // Scan the components under the package and load them into the Spring container@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        (, args);
    }
}

@Controller: Identifies the control layer component, which is actually a specialization of @Component, used to represent a web controller. Process HTTP requests and return view or response data.

@Controller
public class MyController {
    @Autowired
    private final UserService userService;

    @GetMapping("/user")
    public String getUser(Model model) {
        User user = (1);
        ("user", user);
        return "user";
    }
}

@RestController: is a combination of @Controller and @ResponseBody, and the returned object will be automatically serialized to JSON or XML and written to the HTTP response body.

@RestController
public class MyController {
    @Autowired
    private final UserService userService;

    @GetMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

@Service: Identifies the service layer component, which is actually a specialization of @Component, used to represent business logic services.

@Service
public class MyService {
}

@Repository: Identify the persistence layer component (DAO layer), which is actually a specialization of @Component, used to represent the data access component. Commonly used to interact with databases.

@Repository
public interface UserDao {
}

@Bean: Method annotation, used to modify the method. The main function is to add the return object of the modified method to the Spring container, so that other components can use this object through dependency injection.

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

@Configuration: Identify a class as a configuration class, a specialization of @Component, which is usually used with the @Bean annotation.

@Configuration
public class AppConfig {
}

@Scope: Used to declare the scope of a Spring Bean instance, the scope of the scope includes singleton mode, prototype mode (multi-case mode), etc.

@Configuration
public class AppConfig {
    @Bean
    @Scope("prototype")
    public MyPrototypeBean myPrototypeBean() {
        return new MyPrototypeBean();
    }
}

2. Dependency injection

@Autowired: Used to automatically inject dependent objects, annotations provided by the Spring framework.

@RestController
public class MyController {
    @Autowired
    private final UserService userService;

    @GetMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

@Resource: Automatically inject dependent objects by name (can also be type, but by name by default), JDK provides annotations.

@RestController
public class MyController {
    @Resource
    private final UserService userService;

    @GetMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

@Qualifier: Used with @Autowired to specify the name of the bean to inject. When multiple beans of the same type exist, you can use @Qualifier to specify which one to inject.

@RestController
public class MyController {
    @Autowired
    @Qualifier("userService")
    private final UserService us;

    @GetMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

Related

@RequestMapping: Used to map HTTP requests to processing methods, supporting GET, POST, PUT, DELETE and other request methods. Can be marked on a class or method. When labeled on a class, all methods that represent that respond to requests in the class take the class path as the parent path.

@RestController
@RequestMapping("/contoller")
public class MyController {
    @Resource
    private final UserService userService;

    @RequestMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

@GetMapping、@PostMapping、@PutMapping、@DeleteMapping: Used to map HTTP GET, POST, PUT, DELETE requests to processing methods respectively. They are specializations of @RequestMapping, corresponding to different HTTP request methods respectively.

@RestController
@GetMapping("/contoller")
public class MyController {
    @Resource
    private final UserService userService;

    @GetMapping("/user")
    public User getUser() {
        User user = (1);
        return user;
    }
}

@RequestParam: Used to bind request parameters to parameters of the Controller method. It is mainly used to process query parameters in GET, POST and other requests, such as/api?param1=value1&param2=value2The param1 and param2 parameters in   are set to the parameters of the method.

@PathVariable: Used to extract variable values ​​from the requested URL path and bind them to the parameters of the controller method.

@GetMapping("/user/{userId}")
public String getUserById(@PathVariable("userId") Long id) {
    return "User with ID " + id;
}

@RequestBody: Convert the content of the HTTP request body (such as JSON, XML) into a Java object. It is usually used to receive data passed by the front end and labeled on the parameters of the method.

@Controller
public class MyController {
    @PostMapping("/submit")
    public String submitData(@RequestBody MyData myData) {
        (myData);
        return "success";
    }
}

@ResponseBody: Convert the return value of the method to the specified format (such as JSON, XML) and return it to the client as the content of the HTTP response. It is usually used on methods with annotations such as @RequestMapping or @GetMapping.

@RestController
public class MyController {
    @GetMapping("/data")
    @ResponseBody
    public String getData() {
        return "Some data";
    }
}

4. Read the configuration

@Value: Used to inject property values, usually obtained from configuration files. Label on a field and specify the source of the attribute value (such as a property in the configuration file).

@Component
public class MyComponent {
    @Value("${}")
    private String myPropertyValue;

    public void printValue() {
        (myPropertyValue);
    }
}

@ConfigurationProperties: Used to bind configuration properties to an entity class. It is usually used to read property values ​​from a configuration file and bind to fields of a class.

import ;
import ;

@Component
@ConfigurationProperties(prefix = "")
public class MyAppProperties {
    private String property1;
    private int property2;

    // Getters and setters
}

5. Configure startup annotations

@SpringBootApplication: The entry class used to identify SpringBoot applications. It is a combination annotation, including three annotations: @Configuration, @EnableAutoConfiguration and @ComponentScan.

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        (, args);
    }
}

@EnableAutoConfiguration: Enable Spring Boot's automatic configuration mechanism to automatically configure Spring applications based on added dependencies and configuration files.

6. Other common annotations

@Transactional: Declare transaction management. Tagged on a class or method, specifying the propagation behavior, isolation level, etc. of the transaction.

import ;
import ;

@Service
public class MyService {
    @Transactional
    public void performTransactionalOperation() {
        // Database operations
    }
}

@Scheduled: Declare a method that needs to be executed regularly. Mark on the method and specify rules for execution at a time (such as execution every certain time).

import ;
import ;

@Component
public class MyScheduledTask {
    @Scheduled(fixedRate = 5000)
    public void performTask() {
        ("Task executed.");
    }
}

summary

There are many annotations in Spring Boot, and this article also briefly guides you to learn about common annotations in Spring Boot. Of course, these annotations do not need to be remembered all. You only need to have a rough impression. When using them, you can check the specific use.

The above is the detailed content of the commonly used annotations that must be mastered in SpringBoot. For more information about common annotations in SpringBoot, please follow my other related articles!