1. Core startup annotation
1. @SpringBootApplication
- effect: The entry annotation of Spring Boot application, combining @Configuration, @EnableAutoConfiguration and @ComponentScan
- Use scenarios: Must be used on the main startup class
- Example:
@SpringBootApplication public class MyApplication { public static void main(String[] args) { (, args); } }
2. @EnableAutoConfiguration
- effect: Enable Spring Boot's automatic configuration mechanism
- Use scenarios: Used when custom automatic configuration is required
- Notice: Usually it does not need to be used alone, @SpringBootApplication has included
3. @Configuration
- effect: Tagged class as configuration class, replace XML configuration
- Use scenarios: Used when defining the bean configuration
- Example:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } }
4. @ComponentScan
- effect: Automatically scan and register beans to Spring container
- Use scenarios: Used when you need to customize the scan path
- Example:
@SpringBootApplication @ComponentScan({"", ""}) public class MyApplication { // ... }
2. Bean definition and management
1. @Bean
- effect: The object returned by the declared method is managed by Spring
- Use scenarios: The bean that defines third-party library components in the configuration class
- Example:
@Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
2. @Component/@Service/@Repository/@Controller
- effect: Mark the class as a Spring component, corresponding to the general component, service layer, data layer and control layer respectively
- Use scenarios: Select corresponding annotations based on hierarchy when developing business components
- Example:
@Service public class UserServiceImpl implements UserService { // Business logic} @Repository public class UserRepositoryImpl implements UserRepository { // Data access logic}
3. @ConfigurationProperties
- effect: Bind the configuration file attributes to the Bean
- Use scenarios: When centrally managing configuration properties
- Example:
@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private String version; // getters/setters }
4. @Scope
- effect: Define the scope of the bean (singleton, prototype, etc.)
- Use scenarios: When a non-singleton bean is required
- Example:
@Bean @Scope("prototype") public MyPrototypeBean myPrototypeBean() { return new MyPrototypeBean(); }
3. Dependency injection
1. @Autowired
- effect: Automatically inject dependencies by type
- Use scenarios: The first choice is when injecting dependencies
- Example:
@Service public class UserService { @Autowired private UserRepository userRepository; }
2. @Qualifier
- effect: Specify the injected bean name (resolve multiple bean conflicts of the same type)
- Use scenarios: When there are multiple beans of the same type
- Example:
@Autowired @Qualifier("primaryDataSource") private DataSource dataSource;
3. @Value
- effect: Inject property values
- Use scenarios: Inject simple configuration values
- Example:
3. @Value effect:Inject property values Use scenarios:Inject simple configuration values Example:
4. Web MVC development
1. @RestController/@Controller
- effect: Tagged class as web controller
- Use scenarios: Developing REST API or traditional MVC controller
- Example:
@RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { // ... } }
2. @RequestMapping/@GetMapping/@PostMapping, etc.
- effect: Map HTTP request paths and methods
- Use scenarios: Define API endpoints
- Example:
@PostMapping("/create") public ResponseEntity<User> createUser(@RequestBody UserDto userDto) { // ... }
3. @RequestBody/@ResponseBody
- effect: Request body binding and response body conversion
- Use scenarios: REST API development
- Example:
@PostMapping public User create(@RequestBody User user) { return (user); }
4. @PathVariable/@RequestParam
- effect: Get the value from the URL path or parameter
- Use scenarios: Need to get variables or query parameters in the URL
- Example:
@GetMapping("/search") public List<User> searchUsers(@RequestParam String keyword) { // ... }
5. Data access
1. @Entity/@Table
- effect: Define JPA entity class and corresponding table
- Use scenarios: Database table mapping
- Example:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = ) private Long id; // ... }
2. @Transactional
- effect: Declare transactions
- Use scenarios: Methods or classes that require transaction management
- Example:
@Service public class UserService { @Transactional public void updateUser(User user) { // ... } }
3. @RepositoryRestResource
effect: Expose the JPA repository to REST endpoint
Use scenarios: Rapidly develop RESTful data services
Example:
@RepositoryRestResource(path = "users") public interface UserRepository extends JpaRepository<User, Long> { }
6. Test related
1. @SpringBootTest
- effect: Load the complete application context for integration testing
- Use scenarios: Integration testing
- Example:
@SpringBootTest class MyIntegrationTests { @Autowired private MyService myService; // Test method}
2. @WebMvcTest
- effect: Test only the web layer
- Use scenarios: Controller unit test
- Example:
@WebMvcTest() class UserControllerTests { @Autowired private MockMvc mockMvc; // Test method}
7. Advanced Features
1. @EnableCaching/@Cacheable
- effect: Enable cache and declare cacheable methods
- Use scenarios: When the method result cache is required
- Example:
@Service public class UserService { @Cacheable("users") public User getUser(Long id) { // Only the first time will be executed, and subsequently retrieved from the cache } }
2. @EnableScheduling/@Scheduled
- effect: Enable timed tasks and define task execution time
- Use scenarios: When tasks need to be executed regularly
- Example:
@Component public class MyScheduler { @Scheduled(fixedRate = 5000) public void doTask() { // Execute every 5 seconds } }
3. @Async
- effect: The marking method is asynchronous execution
- Use scenarios: Time-consuming operation required asynchronously
- Example:
@Service public class AsyncService { @Async public void asyncMethod() { // Asynchronous execution } }
Best Practice Recommendations
- Clear layering: Strictly follow Controller-Service-Repository layering and use corresponding annotations
- Reasonable use of automatic configuration: Prioritize the use of Spring Boot's automatic configuration, and customize it through @ConfigurationProperties if necessary
- Dependency injection selection: Constructor injection is better than field injection (especially required dependencies)
- Transaction Management: Use @Transactional at the Service layer to keep transaction boundaries clear
- Testing strategies: Select the appropriate test annotation according to the test target (@WebMvcTest for unit tests, @SpringBootTest for integration tests)
- REST API Development: Preferred to use @RestController and HTTP method specific annotations (@GetMapping, etc.)
This is the end of this article about the detailed explanation and usage guide for Spring Boot Common Annotations. For more relevant Spring Boot Common Annotations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!