您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何利用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(如需数据库支持)
src/
├── main/
│ ├── java/
│ │ └── com/example/
│ │ ├── controller/
│ │ ├── model/
│ │ ├── repository/
│ │ └── Application.java
│ └── resources/
│ ├── application.properties
│ └── static/
@Data
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String name;
private BigDecimal price;
@CreationTimestamp
private LocalDateTime createdAt;
}
public interface ProductRepository
extends JpaRepository<Product, Long> {
List<Product> findByNameContaining(String name);
}
@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));
}
}
全局异常处理器:
@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));
}
}
@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) {
// 解析排序参数逻辑
}
添加超媒体链接:
@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());
}
添加依赖:
<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/
@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();
}
}
实现JWT过滤器:
public class JwtFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) {
// 验证JWT逻辑
}
}
@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"));
}
}
@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());
}
}
mvn clean package
添加依赖:
<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 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。