Spring Boot常用注解说明

Spring Boot 是一个基于 Spring 框架的项目,它通过简化配置来帮助开发者快速构建微服务和其他应用程序。在 Spring Boot 中,注解(Annotations)扮演着非常重要的角色,它们用于减少配置和提高代码的可读性。以下是一些常用的 Spring Boot 注解及其详解:

Spring Boot 是一个基于 Spring 框架的项目,它通过简化配置来帮助开发者快速构建微服务和其他应用程序。在 Spring Boot 中,注解(Annotations)扮演着非常重要的角色,它们用于减少配置和提高代码的可读性。以下是一些常用的 Spring Boot 注解及其详解:

  1. @SpringBootApplication

    • 组合了 @Configuration@EnableAutoConfiguration@ComponentScan 注解。
    • 表明该类是一个 Spring Boot 应用的主类。
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MyApp {
        public static void main(String[] args) {
            SpringApplication.run(MyApp.class, args);
        }
    }
    
  2. @RestController

    • 组合了 @Controller@ResponseBody 注解。
    • 表明该类是一个控制器,并且所有的方法返回值都将作为 HTTP 响应的正文。
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @RestController
    public class MyController {
        @GetMapping("/hello")
        public String hello() {
            return "Hello, World!";
        }
    }
    
  3. @RequestMapping

    • 将 HTTP 请求映射到处理器方法。
    • 可以指定请求类型和路径。
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    @Controller
    public class MyController {
        @RequestMapping(value = "/greeting", method = RequestMethod.GET)
        public String greeting() {
            return "greeting";
        }
    }
    
  4. @GetMapping / @PostMapping / @PutMapping / @DeleteMapping

    • 特定类型的 @RequestMapping 快捷方式。
    @GetMapping("/users")
    public List<User> getAllUsers() {
        // ...
    }
    
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        // ...
    }
    
    @PutMapping("/users/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        // ...
    }
    
    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        // ...
    }
    
  5. @Autowired

    • 自动注入依赖的组件。可以用于字段、构造器、设置方法和普通方法。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService {
        private final UserRepository userRepository;
    
        @Autowired
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
        // ...
    }
    
  6. @Service

    • 用于标注服务层组件,通常用于业务逻辑处理。
    @Service
    public class UserService {
        // ...
    }
    
  7. @Repository

    • 用于标注数据访问组件,即DAO组件,表明该类用于数据库操作。
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        // ...
    }
    
  8. @Component

    • 用于标注组件,表明该类由 Spring 管理,通常用于非服务层和非数据层的组件。
    @Component
    public class MyComponent {
        // ...
    }
    
  9. @Configuration

    • 用于定义配置类,可以替代传统的XML配置文件,通常用于定义Bean的创建。
    @Configuration
    public class AppConfig {
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  10. @Bean

    • 在配置类中声明一个 Bean,可以指定Bean的作用域、生命周期等。
    @Configuration
    public class AppConfig {
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }
    
  11. @Value

    • 注入外部配置的值,可以用于字段、构造器、设置方法。
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyComponent {
        @Value("${my.property}")
        private String myProperty;
        // ...
    }
    
  12. @PathVariable

    • 从 URL 中提取变量值,可以指定参数是否必须。
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        // ...
    }
    
  13. @RequestParam

    • 从请求参数中提取值。
    @GetMapping("/users")
    public List<User> getUsersByStatus(@RequestParam String status) {
        // ...
    }
    
  14. @RequestBody

    • 将 HTTP 请求体绑定到方法参数。
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        // ...
    }
    
  15. @ResponseBody

    • 将方法返回值写入 HTTP 响应体。
    @Controller
    public class MyController {
        @ResponseBody
        @GetMapping("/hello")
        public String hello() {
            return "Hello, World!";
        }
    }
    
  16. @EnableAutoConfiguration

    • 根据添加的 jar 依赖自动配置项目。
    @SpringBootApplication // 包含 @EnableAutoConfiguration
    public class MyApp {
        public static void main(String[] args) {
            SpringApplication.run(MyApp.class, args);
        }
    }
    
  17. @Profile

    • 指定某些 Bean 只在特定的环境下创建。
    @Configuration
    @Profile("dev")
    public class DevConfig {
        // ...
    }
    
  18. @Lazy

    • 延迟加载 Bean。
    @Service
    public class MyService {
        private final MyDependency myDependency;
    
        @Autowired
        public MyService(@Lazy MyDependency myDependency) {
            this.myDependency = myDependency;
        }
        // ...
    }
    
  19. @Transactional

    • 声明事务管理。
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class MyService {
        @Transactional
        public void doSomething() {
            // ...
        }
    }
    
  20. @Cacheable

    • 声明缓存方法的结果。
    import org.springframework.cache.annotation.Cacheable;
    
    @Service
    public class MyService {
        @Cacheable("users")
        public User findUser(String user) {
            // ...
        }
    }
    

这些注解和代码示例应该能帮助你更好地理解和使用 Spring Boot 中的注解。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页