Spring 是 Java 企业级开发中最流行的框架之一,提供了 IoC(控制反转)、AOP(面向切面编程)、事务管理等核心功能,并衍生出一系列子项目(如 Spring Boot、Spring Cloud)。以下是 Spring 生态的关键技术和最佳实践:
一、Spring 核心框架
1. IoC 容器与依赖注入
- 核心接口:
BeanFactory和ApplicationContext - 依赖注入方式:
- 构造器注入(推荐):java
@Service public class UserService { private final UserRepository userRepository; @Autowired // 可省略,构造器参数自动注入 public UserService(UserRepository userRepository) { this.userRepository = userRepository; } } - 字段注入(不推荐,不利于测试):java
@Service public class UserService { @Autowired private UserRepository userRepository; }
- 构造器注入(推荐):
2. AOP(面向切面编程)
- 应用场景:日志记录、权限验证、事务管理
- 实现方式:
- 基于注解的声明式 AOP:java
@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); } } - 自定义注解:java
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface LogExecutionTime { } @Aspect @Component public class PerformanceAspect { @Around("@annotation(LogExecutionTime)") public Object logTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); System.out.println("Method " + joinPoint.getSignature().getName() + " took " + (System.currentTimeMillis() - startTime) + "ms"); return result; } }
- 基于注解的声明式 AOP:
3. 事务管理
- 声明式事务(基于 AOP):java
@Service public class UserService { @Autowired private UserRepository userRepository; @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public void transferMoney(Long fromUserId, Long toUserId, BigDecimal amount) { User fromUser = userRepository.findById(fromUserId).orElseThrow(); User toUser = userRepository.findById(toUserId).orElseThrow(); fromUser.setBalance(fromUser.getBalance().subtract(amount)); toUser.setBalance(toUser.getBalance().add(amount)); userRepository.save(fromUser); userRepository.save(toUser); } }
二、Spring Boot
1. 自动配置与起步依赖
- 关键特性:
- 自动配置:根据 classpath 中的依赖自动配置 Bean
- 起步依赖(Starter):简化依赖管理,如
spring-boot-starter-web
- 自定义配置:java
@Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
2. 外部化配置
- 配置文件优先级:
命令行参数 > 系统环境变量 > application-{profile}.properties > application.properties - 读取配置:java
@Component public class AppSettings { @Value("${app.name}") private String appName; @Value("${app.timeout:5000}") // 默认值 private int timeout; }
3. Actuator(生产就绪特性)
- 常用端点:properties
management.endpoints.web.exposure.include=health,info,metrics,prometheus - 自定义健康检查:java
@Component public class DatabaseHealthIndicator implements HealthIndicator { @Autowired private DataSource dataSource; @Override public Health health() { try (Connection connection = dataSource.getConnection()) { return Health.up().build(); } catch (SQLException e) { return Health.down(e).build(); } } }
三、Spring MVC 与 RESTful API
1. 控制器与请求映射
java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = userService.save(user);
return ResponseEntity.created(URI.create("/api/users/" + savedUser.getId())).body(savedUser);
}
}2. 异常处理
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
}
}3. 请求参数校验
java
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
// 处理验证通过的用户
}
public class User {
@NotNull
private String username;
@Email
private String email;
@Min(18)
private int age;
}四、Spring Data
1. JPA 与 Spring Data JPA
- 实体类与仓库接口:java
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; @Column(unique = true) private String email; // getters/setters } public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmail(String email); @Query("SELECT u FROM User u WHERE u.age >= :minAge") List<User> findByMinAge(@Param("minAge") int minAge); }
2. 自定义查询与分页
java
public interface ProductRepository extends JpaRepository<Product, Long> {
Page<Product> findByCategory(String category, Pageable pageable);
@Modifying
@Transactional
@Query("UPDATE Product p SET p.price = p.price * :factor WHERE p.category = :category")
int updatePricesByCategory(@Param("category") String category, @Param("factor") double factor);
}五、Spring Security
1. 基于注解的权限控制
java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.and()
.csrf().disable(); // 仅示例,生产环境需启用
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
}2. JWT 认证
java
@Service
public class JwtService {
private static final String SECRET_KEY = "your-secret-key";
private static final long EXPIRATION_TIME = 86400000; // 24小时
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}六、Spring Cloud(微服务)
1. 服务注册与发现(Eureka/Nacos)
java
// 服务提供者
@SpringBootApplication
@EnableEurekaClient // 或 @EnableDiscoveryClient
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
// 服务消费者
@Autowired
private RestTemplate restTemplate;
@LoadBalanced // 启用客户端负载均衡
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public Product getProduct(Long id) {
return restTemplate.getForObject("http://product-service/api/products/" + id, Product.class);
}2. 配置中心(Config Server)
yaml
# application.yml
spring:
cloud:
config:
uri: http://config-server:8888
name: my-application
profile: dev3. 熔断器(Resilience4j/Hystrix)
java
@Service
public class ProductService {
@Autowired
private RestTemplate restTemplate;
@CircuitBreaker(name = "productService", fallbackMethod = "fallback")
public Product getProduct(Long id) {
return restTemplate.getForObject("http://product-service/api/products/" + id, Product.class);
}
public Product fallback(Long id, Throwable t) {
return new Product(id, "Fallback Product", 0.0);
}
}七、测试与最佳实践
1. 单元测试与集成测试
java
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@MockBean
private UserRepository userRepository;
@Test
public void testCreateUser() {
User user = new User();
user.setUsername("test");
user.setEmail("test@example.com");
when(userRepository.save(any(User.class))).thenReturn(user);
User savedUser = userService.save(user);
assertNotNull(savedUser.getId());
}
}2. 性能调优
- 慢查询监控:properties
spring.jpa.properties.hibernate.generate_statistics=true logging.level.org.hibernate.stat=DEBUG - 连接池配置:properties
spring.datasource.hikari.maximum-pool-size=10 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.idle-timeout=30000
八、Spring 生态扩展
- Spring WebFlux:响应式编程模型,非阻塞 I/O
- Spring Session:分布式会话管理
- Spring Batch:批处理框架
- Spring Integration:企业应用集成(EAI)
- Spring for GraphQL:支持 GraphQL 查询
九、学习资源
- 官方文档:
- 经典书籍:
- 《Spring 实战》(Spring in Action)
- 《Spring Boot 实战》(Spring Boot in Action)
- 实战项目:
- 基于 Spring Boot + Vue.js 的前后端分离项目
- 微服务架构示例(如电商系统)
总结
Spring 框架通过 IoC、AOP 和丰富的子项目,为企业级开发提供了一站式解决方案。建议从 Spring Boot 入手,掌握核心特性(如依赖注入、事务管理)后,再深入学习微服务、安全等高级主题。通过实际项目(如 REST API 开发、分布式系统)巩固技能,结合官方文档和社区资源持续学习。