Spring Boot 常用注解

66 阅读2分钟

Spring Boot 常用注解:一篇干货文章

Spring Boot 是一个用于简化 Spring 应用程序开发的框架,它提供了许多注解来简化配置和开发过程。本文将介绍一些常用的 Spring Boot 注解,帮助您更高效地开发 Spring Boot 应用程序。

1. @SpringBootApplication

@SpringBootApplication 是一个组合注解,它包含了以下三个注解:

  • @Configuration:表示该类是一个配置类。
  • @EnableAutoConfiguration:启用自动配置,让 Spring Boot 根据项目中的依赖自动配置应用程序。
  • @ComponentScan:扫描当前包及其子包下的所有组件。

通常,我们在 Spring Boot 应用程序的主类上使用此注解。

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

2. @RestController

@RestController 是一个组合注解,它包含了 @Controller@ResponseBody@Controller 表示该类是一个控制器类,而 @ResponseBody 表示将返回值直接写入 HTTP 响应体中。这对于构建 RESTful API 非常有用。

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

3. @RequestMapping

@RequestMapping 注解用于映射 HTTP 请求到特定的处理方法。它可以用在类级别和方法级别。在类级别使用时,它表示该类中的所有方法都具有相同的请求路径前缀。在方法级别使用时,它表示该方法处理特定的 HTTP 请求。

@RestController
@RequestMapping("/api")
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "Hello, World!";
    }
}

4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

这些注解是 @RequestMapping 的简化版本,分别对应于 HTTP 的 GET、POST、PUT 和 DELETE 请求方法。它们可以直接用于方法级别。

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }

    @PostMapping("/create")
    public String create() {
        // ...
    }

    @PutMapping("/update")
    public String update() {
        // ...
    }

    @DeleteMapping("/delete")
    public String delete() {
        // ...
    }
}

5. @Autowired

@Autowired 注解用于自动装配 Spring 容器中的 Bean。它可以用在构造函数、属性、setter 方法和配置方法上。

@Service
public class MyService {
    // ...
}

@RestController
public class MyController {
    @Autowired
    private MyService myService;

    // ...
}

6. @Component, @Service, @Repository, @Controller

这些注解用于定义 Spring 容器中的 Bean。@Component 是一个通用注解,而其他注解分别用于特定类型的 Bean。

  • @Service:用于标记服务层组件。
  • @Repository:用于标记数据访问层组件。
  • @Controller:用于标记控制层组件。
@Component
public class MyComponent {
    // ...
}

@Service
public class MyService {
    // ...
}

@Repository
public class MyRepository {
    // ...
}

@Controller
public class MyController {
    // ...
}

7. @Value

@Value 注解用于将配置文件中的属性值注入到 Bean 中。它可以用在属性、setter 方法和构造函数上。

@Service
public class MyService {
    @Value("${my.property}")
    private String myProperty;

    // ...
}

8. @Profile

@Profile 注解用于指定某个 Bean 或配置类只在特定的环境中生效。这对于根据不同环境(如开发、测试和生产)使用不同的配置非常有用。

@Configuration
@Profile("dev")
public class DevConfig {
    // ...
}

@Configuration
@Profile("prod")
public class ProdConfig {
    // ...
}

总结

本文介绍了 Spring Boot 中常用的一些注解,希望能帮助您更高效地开发 Spring Boot 应用程序。当然,Spring Boot 还有许多其他注解,建议您在实际开发过程中不断学习和探索。