本文作为Spring框架的进阶指南,深入讲解高级特性、性能优化、最佳实践等进阶内容。在掌握基础知识的基础上,进一步提升您的Spring框架技能水平,解决实际开发中的复杂问题。
一、高级特性
1.1 Spring AOP深入
- Aspect(切面):横切关注点的模块化
- Join Point(连接点):程序执行过程中的特定点
- Pointcut(切点):匹配连接点的表达式
- Advice(通知):在切点上执行的动作
- Target(目标对象):被代理的对象
- Proxy(代理):AOP创建的代理对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
@Configuration @EnableAspectJAutoProxy public class AopConfig { }
@Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {} @Before("serviceMethods()") public void beforeAdvice(JoinPoint joinPoint) { System.out.println("方法执行前: " + joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "serviceMethods()", returning = "result") public void afterReturningAdvice(JoinPoint joinPoint, Object result) { System.out.println("方法返回: " + result); } @AfterThrowing(pointcut = "serviceMethods()", throwing = "exception") public void afterThrowingAdvice(JoinPoint joinPoint, Exception exception) { System.out.println("方法异常: " + exception.getMessage()); } @Around("serviceMethods()") public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object result = joinPoint.proceed(); long end = System.currentTimeMillis(); System.out.println("方法执行时间: " + (end - start) + "ms"); return result; } }
|
1.2 Spring事务管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @Configuration @EnableTransactionManagement public class TransactionConfig { @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }
@Service @Transactional public class UserService { @Transactional(rollbackFor = Exception.class) public void transferMoney(Long fromId, Long toId, BigDecimal amount) { userRepository.deduct(fromId, amount); userRepository.add(toId, amount); } @Transactional(readOnly = true) public User getUserById(Long id) { return userRepository.findById(id); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void logOperation(String operation) { } }
|
- REQUIRED:如果存在事务则加入,否则创建新事务(默认)
- REQUIRES_NEW:总是创建新事务
- SUPPORTS:如果存在事务则加入,否则非事务执行
- NOT_SUPPORTED:非事务执行,挂起当前事务
- MANDATORY:必须在事务中执行,否则抛出异常
- NEVER:必须在非事务中执行,否则抛出异常
- NESTED:嵌套事务
1.3 Spring Bean生命周期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| @Component public class LifecycleBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean { public LifecycleBean() { System.out.println("1. 构造函数执行"); } @Value("${app.name}") private String appName; @Override public void setBeanName(String name) { System.out.println("3. setBeanName: " + name); } @Override public void setBeanFactory(BeanFactory beanFactory) { System.out.println("4. setBeanFactory"); } @Override public void setApplicationContext(ApplicationContext applicationContext) { System.out.println("5. setApplicationContext"); } @PostConstruct public void postConstruct() { System.out.println("7. @PostConstruct执行"); } @Override public void afterPropertiesSet() { System.out.println("8. afterPropertiesSet执行"); } @PreDestroy public void preDestroy() { System.out.println("12. @PreDestroy执行"); } @Override public void destroy() { System.out.println("13. destroy执行"); } }
|
二、性能优化
2.1 Bean作用域优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @Component public class SingletonBean { }
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @Component public class PrototypeBean { }
@Scope(WebApplicationContext.SCOPE_REQUEST) @Component public class RequestBean { }
@Scope(WebApplicationContext.SCOPE_SESSION) @Component public class SessionBean { }
|
- 单例:无状态Bean,性能最好
- 原型:有状态Bean,线程不安全对象
- 请求/会话:Web相关的Bean
2.2 懒加载优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @Configuration @Lazy public class LazyConfig { }
@Lazy @Component public class LazyBean { public LazyBean() { System.out.println("LazyBean初始化"); } }
@Component public class ServiceBean { @Lazy @Autowired private HeavyBean heavyBean; }
|
2.3 条件装配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @ConditionalOnProperty(name = "feature.enabled", havingValue = "true") @Component public class ConditionalBean { }
public class OnProductionCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String env = context.getEnvironment().getProperty("spring.profiles.active"); return "prod".equals(env); } }
@Conditional(OnProductionCondition.class) @Component public class ProductionBean { }
|
三、架构设计
3.1 设计模式应用
1 2 3 4 5
| @Component public class SingletonService { }
|
1 2 3
| ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = context.getBean(UserService.class);
|
1 2 3 4 5 6
| @Aspect @Component public class ProxyAspect { }
|
1 2 3 4 5 6 7 8
| @Autowired private JdbcTemplate jdbcTemplate;
public List<User> findAll() { return jdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper<>(User.class)); }
|
3.2 模块化设计
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| ┌─────────────────────────────────────┐ │ Controller Layer │ │ - 处理HTTP请求 │ │ - 参数验证 │ │ - 返回响应 │ ├─────────────────────────────────────┤ │ Service Layer │ │ - 业务逻辑 │ │ - 事务管理 │ ├─────────────────────────────────────┤ │ Repository Layer │ │ - 数据访问 │ │ - 数据库操作 │ ├─────────────────────────────────────┤ │ Model Layer │ │ - 实体类 │ │ - DTO/VO │ └─────────────────────────────────────┘
|
四、实战技巧
4.1 调试技巧
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> ```yaml # application.yml management: endpoints: web: exposure: ```json include: "*"
|
endpoint:
health:
show-details: always
1 2 3 4 5 6 7 8
| 查看Bean信息:
```bash # 访问端点 http://localhost:8080/actuator/beans http://localhost:8080/actuator/env http://localhost:8080/actuator/health
|
4.2 问题排查
常见问题及解决方案:
- Bean创建失败
1 2 3 4 5 6 7
| 2. 事务不生效 ```java ```java // 检查@Transactional是否在public方法上 // 检查是否在同一个类中调用 // 检查异常类型是否匹配rollbackFor
|
1 2 3 4 5 6 7
| 3. AOP不生效 ```java ```java // 检查@EnableAspectJAutoProxy // 检查切点表达式 // 检查目标类是否被Spring管理
|
五、总结
通过本文的学习,您已经掌握了Spring框架的进阶知识。在下一篇文章中,我们将通过实际项目案例,展示Spring框架的实战应用。
本文标题: Spring框架进阶篇
发布时间: 2025年02月07日 00:00
最后更新: 2025年12月30日 08:54
原始链接: https://haoxiang.eu.org/e60a371/
版权声明: 本文著作权归作者所有,均采用CC BY-NC-SA 4.0许可协议,转载请注明出处!