admin管理员组文章数量:1439596
springboot常用注解
在Spring Boot的微服务开发实践中,注解驱动编程(Annotation-Driven Programming)彻底改变了传统XML配置的开发模式。掌握核心注解的正确使用,不仅能提升开发效率,更能帮助开发者深入理解框架的设计哲学。本文将系统梳理Spring Boot开发中高频使用的关键注解,并深入解析其应用场景。
一、项目启动与配置核心
- @SpringBootApplication(启动基石) java @SpringBootApplication public class MyApplication { public static void main(String args) { SpringApplication.run(MyApplication.class, args); } } 这个组合注解包含三大核心功能:
@Configuration
:标识为配置类@EnableAutoConfiguration
:启用自动配置魔法@ComponentScan
:开启组件扫描(默认扫描当前包及其子包)
- 条件装配注解(灵活配置的关键) 注解名称 生效条件 应用场景示例
@ConditionalOnProperty 配置文件包含指定属性 多环境配置切换 @ConditionalOnClass Classpath中存在指定类 自动配置类条件加载 @ConditionalOnMissingBean 容器中不存在指定Bean时生效 默认配置覆盖 @ConditionalOnWebApplication 当应用是Web应用时生效 Web相关自动配置
示例:动态配置数据源 java @Configuration public class DataSourceConfig {
代码语言:javascript代码运行次数:0运行复制@Bean
@ConditionalOnProperty(name = "datasource.type", havingValue = "mysql")
public DataSource mysqlDataSource() {
return new MysqlDataSource();
}
@Bean
@ConditionalOnProperty(name = "datasource.type", havingValue = "oracle")
public DataSource oracleDataSource() {
return new OracleDataSource();
}
}
二、Web开发核心注解矩阵
- 控制器层三剑客 java @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity getUser(@PathVariable Long id) { return ResponseEntity.ok(userService.findById(id)); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public void createUser(@Valid @RequestBody UserDto userDto) { userService.create(userDto); } } 关键注解解析:
@RestController
=@Controller
+@ResponseBody
@RequestMapping
支持RESTful风格路径映射- 参数绑定注解:
@PathVariable
,@RequestParam
,@RequestBody
- 全局异常处理 java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ErrorResponse(ex.getMessage())); } }
三、数据持久化核心
- JPA实体映射 java @Entity @Table(name = "articles") public class Article { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 200) private String title; @OneToMany(mappedBy = "article", cascade = CascadeType.ALL) private List comments = new ArrayList<>(); }
- Repository层 java public interface ArticleRepository extends JpaRepository<Article, Long> { @Query("SELECT a FROM Article a WHERE a.publishStatus = :status") List @Modifying @Query("UPDATE Article a SET a.viewCount = a.viewCount + 1 WHERE a.id = :id") void incrementViewCount(@Param("id") Long id); }
四、高级功能注解
- 定时任务配置 java @EnableScheduling @Configuration public class ScheduleConfig { @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行 public void dataBackupTask() { // 执行备份逻辑 } }
- 异步处理 java @EnableAsync @SpringBootApplication public class Application { ... }
@Service public class NotificationService {
代码语言:javascript代码运行次数:0运行复制@Async
public void sendEmail(String to, String content) {
// 异步发送邮件逻辑
}
}
五、测试验证利器 java @SpringBootTest @AutoConfigureMockMvc class UserControllerTest {
代码语言:javascript代码运行次数:0运行复制@Autowired
private MockMvc mockMvc;
@Test
void getExistingUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
六、配置管理艺术
- 自定义配置类 java @ConfigurationProperties(prefix = "app.sms") public class SmsConfig { private String apiKey; private int retryCount; // getters/setters }
@Configuration @EnableConfigurationProperties(SmsConfig.class) public class AppConfig { ... }
- Profile管理 java @Profile("prod") @Configuration public class ProdSecurityConfig extends WebSecurityConfigurerAdapter { // 生产环境安全配置 }
@Profile("dev") @Configuration public class DevSecurityConfig extends WebSecurityConfigurerAdapter { // 开发环境安全配置 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-15,如有侵权请联系 cloudcommunity@tencent 删除public开发配置异步注解本文标签: springboot常用注解
版权声明:本文标题:springboot常用注解 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1747663831a2739588.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论