欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Spring Boot 常用注解详解与使用指南

Spring Boot 常用注解详解与使用指南

2025/5/9 13:32:15 来源:https://blog.csdn.net/weixin_52578852/article/details/147402873  浏览:    关键词:Spring Boot 常用注解详解与使用指南

一、核心启动注解

1. @SpringBootApplication

  • 作用:Spring Boot应用的入口注解,组合了@Configuration、@EnableAutoConfiguration和@ComponentScan

  • 使用场景:主启动类上必须使用

  • 示例

    @SpringBootApplication
    public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
    }

2. @EnableAutoConfiguration

  • 作用:启用Spring Boot的自动配置机制

  • 使用场景:当需要自定义自动配置时使用

  • 注意:通常不需要单独使用,@SpringBootApplication已包含

3. @Configuration

  • 作用:标记类为配置类,替代XML配置

  • 使用场景:定义Bean配置时使用

  • 示例

    @Configuration
    public class AppConfig {@Beanpublic MyService myService() {return new MyServiceImpl();}
    }

4. @ComponentScan

  • 作用:自动扫描并注册Bean到Spring容器

  • 使用场景:需要自定义扫描路径时使用

  • 示例

    @SpringBootApplication
    @ComponentScan({"com.example.main", "com.example.controllers"})
    public class MyApplication {// ...
    }

二、Bean定义与管理

1. @Bean

  • 作用:声明方法返回的对象由Spring管理

  • 使用场景:配置类中定义第三方库组件的Bean

  • 示例

    @Configuration
    public class AppConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
    }

2. @Component/@Service/@Repository/@Controller

  • 作用:将类标记为Spring组件,分别对应通用组件、服务层、数据层和控制层

  • 使用场景:开发业务组件时根据分层选择对应注解

  • 示例

    @Service
    public class UserServiceImpl implements UserService {// 业务逻辑
    }@Repository
    public class UserRepositoryImpl implements UserRepository {// 数据访问逻辑
    }

3. @ConfigurationProperties

  • 作用:将配置文件属性绑定到Bean

  • 使用场景:需要集中管理配置属性时

  • 示例

    @ConfigurationProperties(prefix = "app")
    public class AppProperties {private String name;private String version;// getters/setters
    }

4. @Scope

  • 作用:定义Bean的作用域(singleton, prototype等)

  • 使用场景:需要非单例Bean时

  • 示例

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

三、依赖注入

1. @Autowired

  • 作用:按类型自动注入依赖

  • 使用场景:需要注入依赖时首选

  • 示例

    @Service
    public class UserService {@Autowiredprivate UserRepository userRepository;
    }

2. @Qualifier

  • 作用:指定注入的Bean名称(解决多个同类型Bean冲突)

  • 使用场景:有多个同类型Bean时

  • 示例

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource dataSource;

3. @Value

  • 作用:注入属性值

  • 使用场景:注入简单配置值

  • 示例

    3. @Value
    作用:注入属性值使用场景:注入简单配置值示例:

四、Web MVC开发

1. @RestController/@Controller

  • 作用:标记类为Web控制器

  • 使用场景:开发REST API或传统MVC控制器

  • 示例

    @RestController
    @RequestMapping("/api/users")
    public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {// ...}
    }

2. @RequestMapping/@GetMapping/@PostMapping等

  • 作用:映射HTTP请求路径和方法

  • 使用场景:定义API端点

  • 示例

    @PostMapping("/create")
    public ResponseEntity<User> createUser(@RequestBody UserDto userDto) {// ...
    }

3. @RequestBody/@ResponseBody

  • 作用:请求体绑定和响应体转换

  • 使用场景:REST API开发

  • 示例

    @PostMapping
    public User create(@RequestBody User user) {return userService.save(user);
    }

4. @PathVariable/@RequestParam

  • 作用:从URL路径或参数中获取值

  • 使用场景:需要获取URL中的变量或查询参数

  • 示例

    @GetMapping("/search")
    public List<User> searchUsers(@RequestParam String keyword) {// ...
    }

五、数据访问

1. @Entity/@Table

  • 作用:定义JPA实体类和对应表

  • 使用场景:数据库表映射

  • 示例

    @Entity
    @Table(name = "users")
    public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;// ...
    }

2. @Transactional

  • 作用:声明事务

  • 使用场景:需要事务管理的方法或类

  • 示例

    @Service
    public class UserService {@Transactionalpublic void updateUser(User user) {// ...}
    }

3. @RepositoryRestResource

  • 作用:将JPA仓库暴露为REST端点

  • 使用场景:快速开发RESTful数据服务

  • 示例

    @RepositoryRestResource(path = "users")
    public interface UserRepository extends JpaRepository<User, Long> {
    }

六、测试相关

1. @SpringBootTest

  • 作用:加载完整应用上下文进行集成测试

  • 使用场景:集成测试

  • 示例

    @SpringBootTest
    class MyIntegrationTests {@Autowiredprivate MyService myService;// 测试方法
    }

2. @WebMvcTest

  • 作用:仅测试Web层

  • 使用场景:控制器单元测试

  • 示例

    @WebMvcTest(UserController.class)
    class UserControllerTests {@Autowiredprivate MockMvc mockMvc;// 测试方法
    }

七、高级特性

1. @EnableCaching/@Cacheable

  • 作用:启用缓存和声明可缓存方法

  • 使用场景:需要方法结果缓存时

  • 示例

    @Service
    public class UserService {@Cacheable("users")public User getUser(Long id) {// 只有第一次会执行,后续从缓存获取}
    }

2. @EnableScheduling/@Scheduled

  • 作用:启用定时任务和定义任务执行时间

  • 使用场景:需要定时执行任务时

  • 示例

    @Component
    public class MyScheduler {@Scheduled(fixedRate = 5000)public void doTask() {// 每5秒执行一次}
    }

3. @Async

  • 作用:标记方法为异步执行

  • 使用场景:需要异步执行耗时操作时

  • 示例

    @Service
    public class AsyncService {@Asyncpublic void asyncMethod() {// 异步执行}
    }

最佳实践建议

  1. 分层清晰:严格遵循Controller-Service-Repository分层,使用对应注解

  2. 合理使用自动配置:优先使用Spring Boot的自动配置,必要时通过@ConfigurationProperties自定义

  3. 依赖注入选择:构造函数注入优于字段注入(特别是必选依赖)

  4. 事务管理:在Service层使用@Transactional,保持事务边界清晰

  5. 测试策略:根据测试目标选择合适的测试注解(单元测试用@WebMvcTest,集成测试用@SpringBootTest)

  6. REST API开发:优先使用@RestController和HTTP方法特定注解(@GetMapping等)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词