本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
心血制作,太干货,建议收藏!
一、Spring Boot 核心注解
-
@SpringBootApplication
这是 Spring Boot 项目的核心注解,包含了 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan。
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
二、配置与自动配置
-
@Configuration
声明当前类是一个配置类。
@Configuration public class AppConfig { // Bean definitions here } -
@EnableAutoConfiguration
// 通常包含在@SpringBootApplication中 -
@ComponentScan
自动扫描并加载组件。
@ComponentScan(basePackages = "com.example") public class AppConfig { }
三、定义 Bean
-
@Component
泛指组件。
@Component public class MyComponent { } -
@Service
业务层组件。
@Service public class MyService { } -
@Repository
数据访问组件。
@Repository public class MyRepository { } -
@Controller
控制层组件。
@Controller public class MyController { } -
@RestController
控制层组件,返回数据直接写入 HTTP 响应体。
@RestController public class MyRestController { // ... }
四、依赖注入
- @Autowired
自动注入依赖的 bean。
```
@Service
public class MyService {
@Autowired
private MyRepository repository;
}
```
五、配置属性
- @Value
注入 SpEL 表达式结果。
```
@Component
public class MyComponent {
@Value("${app.name}")
private String appName;
}
```
12. @ConfigurationProperties
绑定外部配置到 Java 对象。
```
@Component
@ConfigurationProperties(prefix = "app.database")
public class DatabaseProperties {
// ...
}
```
六、测试相关
- @SpringBootTest
用于 Spring Boot 集成测试。
```
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyIntegrationTest {
// ...
}
```
14. @MockBean
在测试环境中替换 bean 为 Mock 对象。
```
@SpringBootTest
public class MyServiceTest {
@MockBean
private MyRepository repository;
// ...
}
```
七、RESTful Web 服务
- @GetMapping, @PostMapping, etc.
定义 HTTP 方法映射。
```
@RestController
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// ...
}
}
```
16. @PathVariable
从 URL 路径中提取变量值。
```
// 如上例所示
```
17. @RequestBody
绑定请求体到方法参数。
```
// 如上RESTful Web服务示例所示
```
八、数据验证与绑定
- @Valid
开启方法级别验证。
```
public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
// ...
}
```
19. @NotNull, @Size, @Pattern 等
字段验证注解。
```
public class User {
@NotNull private Long id;
// ... other validations
}
```
九、AOP 相关
- @Aspect
声明一个切面。
```
@Aspect
@Component
public class LoggingAspect {
// ...
}
```
21. @Before, @After, etc.
定义通知类型。
```
// 如AOP相关示例所示
```
十、缓存相关
- @EnableCaching
启用缓存支持。
```
@Configuration
@EnableCaching
public class CachingConfig {
// ...
}
```
23. @Cacheable
标记方法结果可缓存。
```
@Cacheable("users")
public User getUserById(Long id) {
// ...
}
```
十一、事务管理
- @Transactional
声明式事务管理。
```
@Service
public class UserService {
@Transactional
public void createUser(User user) {
// ...
}
}
```
十二、任务调度
- @EnableScheduling
启用任务调度支持。
```
@Configuration
@EnableScheduling
public class SchedulingConfig {
// ...
}
```
26. @Scheduled
定义定时任务。
```
@Scheduled(fixedRate = 5000)
public void doSomething() {
// ...
}
```
十三、消息队列
- @RabbitListener
RabbitMQ 消息监听器。
```
@RabbitListener(queues = "myQueue")
public void receiveMessage(String message) {
// ...
}
```
十四、缓存(注意:与 “缓存相关” 重复,这里提供其他缓存注解)
- @CachePut
更新缓存中的数据。
```
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// ...
}
```
29. @CacheEvict
清除缓存条目(已在 “缓存相关” 中给出示例)。
十五、日志记录
- @Slf4j (Lombok 提供)
自动生成 SLF4J 的 Logger 实例。
```
@Slf4j
public class MyService {
public void doSomething() {
log.info("Doing something...");
}
}
```
十六、异步执行
- @EnableAsync
启用异步方法执行支持。
```
@Configuration
@EnableAsync
public class AsyncConfig {
// ...
}
```
32. @Async
标记方法为异步执行。
```
@Async
public void asyncMethod() {
// ...
}
```
十七、异常处理
- @ControllerAdvice
全局异常处理。
```
@ControllerAdvice
public class GlobalExceptionHandler {
// ...
}
```
34. @ExceptionHandler
处理特定异常。
```
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException(Exception e) {
// ...
}
```
十八、事件监听
- @EventListener
监听并处理应用程序事件。
```
@EventListener
public void handleApplicationEvent(ApplicationEvent event) {
// ...
}
```
十九、安全性
- @EnableWebSecurity
启用 Spring Security 的 Web 安全性。
```
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ...
}
```
37. @PreAuthorize, @Secured 等
方法级别的安全性注解。
```
@PreAuthorize("hasRole('ROLE_USER')")
public void secureMethod() {
// ...
}
```
二十、条件化配置
- @ConditionalOnClass
用法说明:当类路径中存在指定的类时,才注册 bean。
@Configuration
@ConditionalOnClass(DataSource.class)
public class DataSourceConfig {
// ...
}
- @ConditionalOnMissingBean
用法说明:当 Spring 容器中不存在指定类型的 bean 时,才注册 bean。
@Bean
@ConditionalOnMissingBean
public MyBean myBean() {
return new MyBean();
}
- @ConditionalOnProperty
用法说明:根据配置文件中的属性值来条件化地注册 bean。
@Configuration
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureConfig {
// ...
}
二十一、Spring Data JPA 相关
- @Entity
用法说明:标记一个类为实体类,映射到数据库中的一个表。
@Entity
public class User {
// ...
}
- @Id
用法说明:标注用于标识实体的属性,通常映射到数据库表的主键列。
@Entity
public class User {
@Id
private Long id;
// ...
}
- @RepositoryRestResource
用法说明:与 Spring Data REST 一起使用,为 JPA 仓库暴露 RESTful API。
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends JpaRepository<User, Long> {
// ...
}
二十二、Web 相关扩展
- @ControllerAdvice (已在异常处理中给出示例)
用法说明(扩展):除了异常处理,还可以用于全局数据绑定、请求预处理等。
- @InitBinder
用法说明:在 Web 控制器中自定义数据绑定方法。
@InitBinder
public void initBinder(WebDataBinder binder) {
// 自定义数据绑定逻辑
}
二十三、Spring MVC 相关
- @ModelAttribute
用法说明:绑定请求参数到模型属性,或者暴露一个方法参数为模型属性。
@ModelAttribute
public void populateModel(@RequestParam String attributeName, Model model) {
model.addAttribute(attributeName, "attributeValue");
}
- @SessionAttributes
用法说明:将模型属性存储到 HTTP session 中。
@Controller
@SessionAttributes("attributeName")
public class MyController {
// ...
}
二十四、性能监控与指标
- @EnableWebMvcMetrics (Spring Boot Actuator 提供)
用法说明:启用 Web MVC 的度量收集,如 HTTP 请求计数器、响应时间等。
// 通常通过添加spring-boot-starter-actuator依赖并配置相关属性来启用
二十五、国际化与本地化
- @MessageSource
用法说明:与 Spring 的国际化支持一起使用,定义消息源。
@Configuration
public class MessageSourceConfig {
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages"); // 假设资源文件名为messages.properties
return messageSource;
}
}
这些注解覆盖了 Spring Boot 开发的多个方面,从核心功能到 Web 服务、数据访问、安全性、国际化等。正确使用这些注解可以大大提高开发效率和代码质量。
如果你渴望深入了解这 50 个注解的完整内容,想要获取更全面的知识和指导,那么请立即行动!关注我们,了解更多 java 和 web 前端学习干货。