如何利用SpringBoot创建Rest接口API

发布时间:2021-09-15 17:32:56 作者:小新
来源:亿速云 阅读:189
# 如何利用SpringBoot创建Rest接口API

## 前言

在现代Web开发中,RESTful API已成为前后端分离架构的核心通信方式。Spring Boot凭借其"约定优于配置"的理念和丰富的Starter依赖,让开发者能够快速构建生产级的REST服务。本文将详细介绍使用Spring Boot创建REST API的全流程,涵盖从环境搭建到高级特性的完整实践。

## 一、环境准备

### 1.1 开发工具要求
- JDK 1.8或更高版本
- Maven 3.5+ 或 Gradle 6.x
- IDE(推荐IntelliJ IDEA或STS)
- Postman(API测试工具)

### 1.2 初始化项目
通过Spring Initializr创建项目:
```bash
https://start.spring.io/

选择依赖: - Spring Web(包含Spring MVC和嵌入式Tomcat) - Lombok(简化POJO编写) - Spring Data JPA(如需数据库支持)

二、基础REST API实现

2.1 项目结构

src/
├── main/
│   ├── java/
│   │   └── com/example/
│   │       ├── controller/
│   │       ├── model/
│   │       ├── repository/
│   │       └── Application.java
│   └── resources/
│       ├── application.properties
│       └── static/

2.2 创建实体类

@Data
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotBlank
    private String name;
    
    private BigDecimal price;
    
    @CreationTimestamp
    private LocalDateTime createdAt;
}

2.3 实现Repository

public interface ProductRepository 
    extends JpaRepository<Product, Long> {
    
    List<Product> findByNameContaining(String name);
}

2.4 编写Controller

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {
    
    private final ProductRepository repository;

    @GetMapping
    public ResponseEntity<List<Product>> getAll() {
        return ResponseEntity.ok(repository.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getById(@PathVariable Long id) {
        return repository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Product> create(@Valid @RequestBody Product product) {
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(repository.save(product));
    }
}

三、REST API进阶特性

3.1 异常处理

全局异常处理器:

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(
            EntityNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(new ErrorResponse(ex.getMessage()));
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(
            MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
                
        return ResponseEntity.badRequest()
                .body(new ErrorResponse("Validation failed", errors));
    }
}

3.2 分页与排序

@GetMapping
public ResponseEntity<Page<Product>> getAll(
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size,
        @RequestParam(defaultValue = "name,asc") String[] sort) {
    
    Pageable pageable = PageRequest.of(page, size, 
            Sort.by(parseSort(sort)));
    return ResponseEntity.ok(repository.findAll(pageable));
}

private Sort.Order[] parseSort(String[] sort) {
    // 解析排序参数逻辑
}

3.3 HATEOAS支持

添加超媒体链接:

@GetMapping("/{id}")
public ResponseEntity<EntityModel<Product>> getById(@PathVariable Long id) {
    return repository.findById(id)
            .map(product -> {
                EntityModel<Product> model = EntityModel.of(product);
                model.add(linkTo(methodOn(ProductController.class)
                        .getById(id)).withSelfRel());
                return ResponseEntity.ok(model);
            })
            .orElse(ResponseEntity.notFound().build());
}

四、API文档生成

4.1 集成Swagger

添加依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

配置类:

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Product API")
                .description("API for product management")
                .version("1.0")
                .build();
    }
}

访问地址:http://localhost:8080/swagger-ui/

五、安全防护

5.1 添加Spring Security

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/public/**").permitAll()
            .antMatchers("/api/**").authenticated()
            .and()
            .httpBasic();
    }
}

5.2 JWT集成(可选)

实现JWT过滤器:

public class JwtFilter extends OncePerRequestFilter {
    
    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, 
            FilterChain filterChain) {
        // 验证JWT逻辑
    }
}

六、测试与验证

6.1 单元测试

@WebMvcTest(ProductController.class)
class ProductControllerTest {
    
    @MockBean
    private ProductRepository repository;
    
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    void shouldReturnProduct() throws Exception {
        Product product = new Product(1L, "Test", BigDecimal.TEN);
        given(repository.findById(1L)).willReturn(Optional.of(product));
        
        mockMvc.perform(get("/api/products/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value("Test"));
    }
}

6.2 集成测试

@SpringBootTest
@AutoConfigureMockMvc
class ProductApiIntegrationTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @Test
    void shouldCreateProduct() throws Exception {
        String json = "{\"name\":\"New\",\"price\":99.99}";
        
        mockMvc.perform(post("/api/products")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isCreated());
    }
}

七、部署与监控

7.1 打包应用

mvn clean package

7.2 Actuator健康监控

添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

配置端点:

management.endpoints.web.exposure.include=health,info,metrics

结语

通过本文的实践,我们完成了从零开始构建Spring Boot REST API的全过程。实际项目中还需要考虑: - API版本控制 - 缓存策略 - 限流防护 - 分布式追踪 - CI/CD流水线

Spring Boot生态提供了所有这些需求的解决方案,开发者可以根据项目规模灵活选择实施方案。

提示:完整示例代码可参考GitHub仓库 spring-boot-rest-example “`

推荐阅读:
  1. hbase REST API
  2. rest api是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot rest api

上一篇:如何解决cssdisplaynlineblock的兼容性问题

下一篇:Linux操作系统有哪些发行版本

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》