Java学习第五十三部分——后端常用函数
目录
一. 前言提要
二. 常用函数
1. Spring Boot核心注解
2. 控制器(Controller)核心方法
3. 服务层(Service)常用方法
4. 数据访问层(Repository)核心方法
5. 数据处理与工具函数
6. 异常处理
7. 文件操作
8. 安全相关(Spring Security)
9. 异步处理
10. 单元测试(JUnit 5 + Mockito)
三. 关键总结
一. 前言提要
在Java后端开发中,针对于Web应用开发(如Spring Boot项目),本文介绍相关常用函数,方法及解释。
二. 常用函数
1. Spring Boot核心注解
| 注解 | 解释 |
|------|------|
| `@RestController` | 定义RESTful控制器,自动将返回值转为JSON |
| `@GetMapping/@PostMapping` | 定义HTTP端点映射(GET/POST请求) |
| `@RequestMapping` | 通用请求映射,可指定方法类型 |
| `@PathVariable` | 获取URL路径参数(如`/users/{id}`) |
| `@RequestParam` | 获取URL查询参数(如`?name=John`) |
| `@RequestBody` | 将HTTP请求体(JSON)绑定到Java对象 |
| `@Autowired` | 自动依赖注入(如Service注入Controller) |
2. 控制器(Controller)核心方法
// 示例:用户控制器
@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;// 获取用户列表@GetMappingpublic List<User> getAllUsers() {return userService.findAll();}// 创建用户(接收JSON)@PostMappingpublic ResponseEntity<User> createUser(@RequestBody User user) {User savedUser = userService.save(user);return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);}// 根据ID查询用户@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.findById(id).orElseThrow(() -> new UserNotFoundException(id));}
}
3. 服务层(Service)常用方法
@Service
public class UserService {@Autowiredprivate UserRepository userRepository;// 保存实体public User save(User user) {return userRepository.save(user); // JPA的save()方法}// 查询所有public List<User> findAll() {return userRepository.findAll(); // JPA的findAll()方法}// 条件查询(示例:按名称查询)public List<User> findByName(String name) {return userRepository.findByNameContainingIgnoreCase(name);}// 业务逻辑处理(示例:用户注册)public User register(UserRegistrationDto dto) {if (userRepository.existsByEmail(dto.getEmail())) {throw new EmailExistsException(dto.getEmail());}User user = new User();user.setEmail(dto.getEmail());user.setPassword(passwordEncoder.encode(dto.getPassword()));return userRepository.save(user);}
}
4. 数据访问层(Repository)核心方法
// JpaRepository提供的基础方法
public interface UserRepository extends JpaRepository<User, Long> {// 自定义查询方法(自动实现)Optional<User> findByEmail(String email);List<User> findByNameContainingIgnoreCase(String name);// 自定义JPQL查询@Query("SELECT u FROM User u WHERE u.status = :status")List<User> findActiveUsers(@Param("status") UserStatus status);// 原生SQL查询@Query(value = "SELECT * FROM users WHERE created_at > :date", nativeQuery = true)List<User> findUsersAfterDate(@Param("date") LocalDateTime date);
}
5. 数据处理与工具函数
集合操作
List<User> users = userRepository.findAll();// 过滤
List<User> activeUsers = users.stream().filter(user -> user.isActive()).collect(Collectors.toList());// 转换
List<String> names = users.stream().map(User::getName).collect(Collectors.toList());// 分组
Map<UserRole, List<User>> usersByRole = users.stream().collect(Collectors.groupingBy(User::getRole));
日期处理(Java 8+)
LocalDateTime now = LocalDateTime.now(); // 当前时间
LocalDate tomorrow = LocalDate.now().plusDays(1); // 明天// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);// 解析
LocalDateTime parsed = LocalDateTime.parse("2023-01-01 12:00:00", formatter);
6. 异常处理
// 自定义异常
public class UserNotFoundException extends RuntimeException {public UserNotFoundException(Long id) {super("用户ID不存在: " + id);}
}// 全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler {@ResponseStatus(HttpStatus.NOT_FOUND)@ExceptionHandler(UserNotFoundException.class)public ErrorResponse handleUserNotFound(UserNotFoundException ex) {return new ErrorResponse(ex.getMessage(), 404);}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(MethodArgumentNotValidException.class)public ErrorResponse handleValidationExceptions(MethodArgumentNotValidException ex) {// 处理参数验证错误}
}
7. 文件操作
// 文件上传
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {String fileName = file.getOriginalFilename();Path path = Paths.get("uploads/" + fileName);Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);return "文件上传成功: " + fileName;
}// 文件下载
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {Path path = Paths.get("uploads/" + filename);Resource resource = new FileSystemResource(path);return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").body(resource);
}
8. 安全相关(Spring Security)
@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().formLogin().and().httpBasic();return http.build();}// 密码编码器@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}
9. 异步处理
@Service
public class AsyncService {@Async // 启用异步执行public CompletableFuture<String> asyncTask() {// 模拟耗时操作Thread.sleep(5000);return CompletableFuture.completedFuture("任务完成");}
}// 调用异步方法
@GetMapping("/async")
public CompletableFuture<String> asyncEndpoint() {return asyncService.asyncTask();
}
10. 单元测试(JUnit 5 + Mockito)
@ExtendWith(MockitoExtension.class)
class UserServiceTest {@Mockprivate UserRepository userRepository;@InjectMocksprivate UserService userService;@Testvoid testFindById() {// 模拟数据User mockUser = new User(1L, "test@example.com");when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));// 调用测试方法User user = userService.findById(1L);// 验证结果assertEquals("test@example.com", user.getEmail());verify(userRepository).findById(1L);}
}
三. 关键总结
1. **分层架构**:Controller(API入口) → Service(业务逻辑) → Repository(数据访问)
2. **依赖注入**:使用`@Autowired`管理组件依赖
3. **JPA简化数据库操作**:`save()`, `findById()`, `findAll()`等
4. **Stream API**:Java 8+的流式操作处理集合数据
5. **全局异常处理**:统一处理系统异常和业务异常
6. **声明式安全**:Spring Security配置访问控制
7. **异步编程**:`@Async`提升系统吞吐量
8. **测试驱动**:Mockito模拟依赖进行单元测试
掌握这些核心函数和方法,能够高效构建健壮的Java后端服务,特别是结合Spring Boot生态时,可以快速开发RESTful API、处理数据库交互、实现安全控制等关键功能。