Spring AOP、性能优化和常用进阶用法。
一、高级特性
1.1 Spring AOP深入
AOP核心概念
- Aspect(切面):横切关注点的模块化
- Join Point(连接点):程序执行过程中的特定点
- Pointcut(切点):匹配连接点的表达式
- Advice(通知):在切点上执行的动作
- Target(目标对象):被代理的对象
- Proxy(代理):AOP创建的代理对象
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生命周期
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作用域优化
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 调试技巧
使用Spring Boot Actuator
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
|
application.yml
management:
endpoints:
web:
exposure:
include: “*”
endpoint:
health:
show-details: always
访问端点
http://localhost:8080/actuator/beans
http://localhost:8080/actuator/env
http://localhost:8080/actuator/health
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
| #### 4.2 问题排查
常见问题及解决方案:
1. Bean创建失败
2. 事务不生效 java
3. AOP不生效 java
### 五、总结
通过本文的学习,您已经掌握了Spring框架的进阶知识。在下一篇文章中,我们将通过实际项目案例,展示Spring框架的实战应用。
|
本文标题: Spring进阶
发布时间: 2026年09月16日 13:40
最后更新: 2026年09月15日 04:00
原始链接: https://haoxiang.eu.org/e60a371/
版权声明: 本文著作权归作者所有,均采用CC BY-NC-SA 4.0许可协议,转载请注明出处!