Spring Boot 常用注解 分类详解,涵盖核心功能、Web开发、数据访问、配置管理、测试等场景
一、核心启动与配置
1. @SpringBootApplication
- 作用:主启动类注解,组合了
@Configuration
、@EnableAutoConfiguration
和@ComponentScan
。 - 示例:
@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
2. @EnableAutoConfiguration
- 作用:启用 Spring Boot 的自动配置机制。
- 示例:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
3. @Configuration
- 作用:标记类为配置类,替代 XML 配置。
- 示例:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }
4. @ComponentScan
- 作用:指定 Spring 扫描组件的包路径。
- 示例:
@ComponentScan(basePackages = "com.example")
二、依赖注入与组件管理
1. @Component
- 作用:通用组件标记(如工具类)。
- 示例:
@Component public class MyComponent { ... }
2. @Service
/ @Repository
/ @Controller
- 作用:分层标记组件(业务层、数据层、控制层)。
- 示例:
@Service public class UserService { ... } @Repository public interface UserRepository extends JpaRepository<User, Long> { ... } @Controller public class HomeController { ... }
3. @Autowired
- 作用:自动注入依赖(按类型匹配)。
- 示例:
@Autowired private UserService userService;
4. @Bean
- 作用:在配置类中定义 Bean。
- 示例:
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
5. @Qualifier
- 作用:按名称注入 Bean(解决歧义性)。
- 示例:
@Autowired @Qualifier("mysqlDataSource") private DataSource dataSource;
三、Web开发与REST API
1. @RestController
- 作用:声明 REST 控制器(返回 JSON/XML)。
- 示例:
@RestController public class UserController { @GetMapping("/users") public List<User> getUsers() { ... } }
2. HTTP方法注解
@GetMapping
/@PostMapping
/@PutMapping
/@DeleteMapping
- 示例:
@PostMapping("/users") public User createUser(@RequestBody User user) { ... }
3. @RequestMapping
- 作用:通用请求映射(支持指定路径和 HTTP 方法)。
- 示例:
@RequestMapping(value = "/api", method = RequestMethod.GET)
4. @PathVariable
/ @RequestParam
- 示例:
@GetMapping("/users/{id}") public User getUser(@PathVariable Long id, @RequestParam String name) { ... }
5. @RequestBody
/ @ResponseBody
- 作用:绑定请求体或直接返回响应体。
- 示例:
@PostMapping("/users") public User createUser(@RequestBody User user) { ... }
6. @CrossOrigin
- 作用:允许跨域请求。
- 示例:
@CrossOrigin(origins = "http://localhost:3000") @RestController public class ApiController { ... }
四、配置与属性绑定
1. @Value
- 作用:注入配置文件中的属性。
- 示例:
@Value("${app.name}") private String appName;
2. @ConfigurationProperties
- 作用:批量绑定配置到 Java 对象。
- 示例:
@ConfigurationProperties(prefix = "app") public class AppConfig { private String name; private int version; }
3. @PropertySource
- 作用:加载外部配置文件。
- 示例:
@PropertySource("classpath:custom.properties")
4. @Profile
- 作用:指定 Bean 生效的环境(如
dev
/prod
)。 - 示例:
@Profile("dev") @Bean public DataSource devDataSource() { ... }
五、数据访问与JPA
1. @Entity
- 作用:声明 JPA 实体类。
- 示例:
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; }
2. @Table
/ @Column
- 作用:定义数据库表和字段映射。
- 示例:
@Table(name = "users") public class User { @Column(name = "user_name") private String name; }
3. @Repository
- 作用:标记数据访问层组件。
- 示例:
@Repository public interface UserRepository extends JpaRepository<User, Long> { ... }
4. @Transactional
- 作用:声明事务管理。
- 示例:
@Transactional public void updateUser(User user) { ... }
5. @Query
- 作用:自定义 JPA 查询。
- 示例:
@Query("SELECT u FROM User u WHERE u.name = ?1") List<User> findByName(String name);
六、测试相关
1. @SpringBootTest
- 作用:启动完整 Spring 上下文进行集成测试。
- 示例:
@SpringBootTest class UserServiceTest { @Autowired private UserService userService; }
2. @WebMvcTest
- 作用:仅加载 Web 层进行测试。
- 示例:
@WebMvcTest(UserController.class) class UserControllerTest { @Autowired private MockMvc mockMvc; }
3. @MockBean
- 作用:向测试上下文注入 Mock 对象。
- 示例:
@MockBean private UserRepository userRepository;
4. @Test
- 作用:标记测试方法(JUnit)。
- 示例:
@Test void testCreateUser() { ... }
七、条件注解与自动配置
1. @ConditionalOnProperty
- 作用:根据配置属性条件加载 Bean。
- 示例:
@ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true")
2. @ConditionalOnClass
- 作用:类路径存在指定类时加载 Bean。
- 示例:
@ConditionalOnClass(RedisTemplate.class)
3. @ConditionalOnMissingBean
- 作用:容器中不存在指定 Bean 时加载。
- 示例:
@ConditionalOnMissingBean(name = "dataSource")
八、其他实用注解
1. @Scheduled
- 作用:定时任务(需
@EnableScheduling
)。 - 示例:
@Scheduled(cron = "0 0 12 * * ?") public void dailyTask() { ... }
2. @Async
- 作用:异步执行方法(需
@EnableAsync
)。 - 示例:
@Async public void asyncTask() { ... }
3. @Cacheable
/ @CacheEvict
- 作用:缓存方法结果或清除缓存。
- 示例:
@Cacheable(value = "users", key = "#id") public User getUser(Long id) { ... } @CacheEvict(value = "users", allEntries = true) public void clearCache() { ... }
4. @EnableAspectJAutoProxy
- 作用:启用 AOP 代理。
- 示例:
@EnableAspectJAutoProxy @Configuration public class AppConfig { ... }
九、安全相关(Spring Security)
1. @EnableWebSecurity
- 作用:启用 Spring Security 配置。
- 示例:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }
2. @PreAuthorize
/ @PostAuthorize
- 作用:方法级权限控制。
- 示例:
@PreAuthorize("hasRole('ADMIN')") public void deleteUser(Long id) { ... }
3. @Secured
- 作用:标记方法需要的角色。
- 示例:
@Secured("ROLE_ADMIN") public void adminMethod() { ... }
总结
场景 | 核心注解 |
---|---|
核心启动 | @SpringBootApplication , @EnableAutoConfiguration , @ComponentScan |
依赖注入 | @Component , @Service , @Autowired , @Bean |
Web开发 | @RestController , @GetMapping , @PostMapping , @RequestBody |
数据访问 | @Entity , @Repository , @Transactional , @Query |
配置管理 | @Value , @ConfigurationProperties , @Profile |
测试 | @SpringBootTest , @WebMvcTest , @MockBean |
高级功能 | @Scheduled , @Async , @Cacheable , @ConditionalOnProperty |
通过合理组合这些注解,可以快速构建 Spring Boot 应用。更多细节可参考 Spring Boot 官方文档。