从零开始学习JavaWeb-7
JavaWeb 学习之旅 Day 7 的深度笔记,聚焦 Spring 框架核心原理与整合实战,涵盖 IoC、AOP、Spring MVC 等企业级开发技术,结合性能优化与安全设计,助你从分层架构迈向框架化开发。
一、Spring 框架核心概念
1. 传统开发痛点 vs Spring 解决方案
痛点
Spring 方案
技术实现
对象耦合度高
控制反转(IoC)
容器管理 Bean 生命周期
业务逻辑混杂重复代码
面向切面编程(AOP)
动态代理实现日志/事务统一处理
配置繁琐
注解驱动开发
@Component
、@Autowired
资源管理复杂
依赖注入(DI)
自动装配 Bean 依赖关系
✅ Spring 核心价值:
解耦:对象由容器创建管理,开发者专注业务逻辑。
模块化:按需引入模块(如 Spring MVC、Spring JDBC)。
二、IoC 容器与 Bean 管理
1. IoC 容器工作原理
graph TB A[配置文件/注解] --> B[BeanDefinition 解析] B --> C[BeanFactory 初始化] C --> D[依赖注入:解决 Bean 引用] D --> E[Bean 实例化]
关键步骤:
-
解析
applicationContext.xml
或注解定义 Bean。 -
容器实例化 Bean 并注入依赖(如
DataSource
)。
2. Bean 作用域与生命周期
作用域
特点
使用场景
singleton
单例(默认)
无状态服务(如 DAO)
prototype
每次请求创建新实例
含状态的 Bean
request
/session
Web 请求/会话级别
用户登录信息
生命周期回调:
public class MyBean implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() { // 初始化逻辑 } @Override public void destroy() { // 销毁逻辑 }}
三、AOP 编程与实战
1. AOP 核心概念
-
切面(Aspect):横切关注点(如日志、事务)。
-
通知(Advice):
-
@Before
:方法执行前 -
@AfterReturning
:成功返回后 -
@Around
:包裹目标方法(最强大)
-
-
切点(Pointcut):定义拦截位置(如
execution(* com.example.service.*.*(..))
)。
2. 声明式事务管理
@Configuration@EnableTransactionManagementpublic class AppConfig { @Bean public DataSource dataSource() { return new HikariDataSource(); // 连接池 } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); }}@Servicepublic class UserService { @Transactional(rollbackFor = Exception.class) public void transferMoney(Account from, Account to, double amount) { // 转账逻辑(异常时自动回滚) }}
💡 对比编程式事务:
声明式:通过注解/XML 配置,代码零侵入。
编程式:手动调用
TransactionTemplate
,灵活性高但冗余。
四、Spring 整合 JavaWeb 项目
1. Spring MVC 核心流程
sequenceDiagram 用户->>DispatcherServlet: HTTP 请求 DispatcherServlet->>HandlerMapping: 查找处理器 HandlerMapping->>Controller: 映射请求 Controller->>Service: 调用业务 Service->>DAO: 数据操作 DAO-->>Service: 返回结果 Service-->>Controller: 处理结果 Controller->>ViewResolver: 选择视图 ViewResolver-->>DispatcherServlet: 视图对象 DispatcherServlet->>用户: 渲染 HTML
关键组件:
-
DispatcherServlet
:前端控制器(统一入口)。 -
@Controller
:处理请求并返回模型数据。
2. RESTful API 设计
@RestController@RequestMapping(\"/api/users\")public class UserController { @Autowired private UserService userService; @GetMapping(\"/{id}\") public ResponseEntity getUser(@PathVariable int id) { User user = userService.findById(id); return ResponseEntity.ok(user); } @PostMapping public ResponseEntity createUser(@RequestBody User user) { userService.save(user); return ResponseEntity.status(HttpStatus.CREATED).build(); }}
设计规范:
-
资源路径:
/资源名/{id}
-
HTTP方法:GET(查询)、POST(创建)、PUT(更新)、DELETE(删除)
五、安全与性能优化
1. Spring Security 基础配置
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(\"/admin/**\").hasRole(\"ADMIN\") .antMatchers(\"/user/**\").authenticated() .anyRequest().permitAll() .and() .formLogin(); }}
功能:
-
角色权限控制
-
表单登录/注销
-
CSRF 防护(默认启用)
2. 缓存优化策略
缓存层级
技术方案
性能提升
数据库缓存
MySQL 查询缓存
读性能 ↑ 30%
应用层缓存
Spring @Cacheable
响应时间 ↓ 70%
分布式缓存
Redis 集群
吞吐量 ↑ 5x
示例:
@Servicepublic class ProductService { @Cacheable(value = \"products\", key = \"#id\") public Product getById(int id) { return productDao.findById(id); // 仅首次查询数据库 }}
六、综合实战:Spring 整合项目重构
1. 重构 Day 6 商品管理系统
架构升级:
src/├── main/│ ├── java/│ │ ├── com.example.config # Spring 配置类│ │ ├── com.example.controller # Spring MVC 控制器│ │ ├── com.example.service # 业务层(含事务)│ │ ├── com.example.dao # 数据层(MyBatis 接口)│ ├── resources/│ │ ├── application.yml # Spring Boot 配置│ │ └── mybatis-config.xml # MyBatis 映射
关键代码:
// Controller 层简化@Controllerpublic class ProductController { @Autowired private ProductService productService; @GetMapping(\"/products\") public String list(Model model) { model.addAttribute(\"products\", productService.findAll()); return \"product/list\"; }}// Service 层事务控制@Servicepublic class ProductServiceImpl implements ProductService { @Autowired private ProductDao productDao; @Transactional @Override public void save(Product product) { productDao.insert(product); }}
2. 前后端分离改造
技术栈:
-
后端:Spring Boot + Spring Security + MyBatis
-
前端:Vue.js 通过 Axios 调用 REST API
接口示例:
// 前端调用axios.get(\'/api/products\') .then(response => { this.products = response.data; });
七、总结与核心对比
技术
原生 JavaWeb
Spring 整合后
优势
对象创建
new
关键字硬编码
IoC 容器管理
解耦、易测试
事务控制
手动 commit/rollback
@Transactional
注解
声明式、代码简洁
安全防护
Filter 手动实现
Spring Security 配置
标准化、功能全面
性能优化
连接池独立配置
@Cacheable
+ Redis
开箱即用、扩展性强
学习进度:
✅ Day 1~3: Servlet/JSP/EL/JSTL 基础 ✅ Day 4~5: JDBC/连接池/事务 ✅ Day 6: MVC 分层架构 ✅ **Day 7: Spring 整合与框架进阶** ➡️ Day 8: Spring Boot 自动化开发
“框架不是银弹,却是提效的杠杆”
掌握 Spring 核心思想(IoC、AOP、声明式编程),后续学习 Spring Boot 将事半功倍!