好的,我将为你梳理JavaWeb从入门到进阶的核心路径,重点解析SpringBoot原理及Bean对象管理。以下是结构化学习框架:
一、JavaWeb基础铺垫
-
Servlet核心机制
- 生命周期:
init() -> service() -> destroy() - 请求处理流程:
\\text{HTTP Request} \\rightarrow \\text{Web容器} \\rightarrow \\text{Filter链} \\rightarrow \\text{Servlet}
java// 简单Servlet示例 @WebServlet("/demo") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { resp.getWriter().print("Hello World"); } } - 生命周期:
-
JSP与MVC雏形
- 表达式语言EL:
${user.name} - JSTL标签库:
<c:forEach items="${list}" var="item">
- 表达式语言EL:
二、SpringBoot核心原理
1. 自动配置(Auto-Configuration)
-
机制本质 :基于条件注解
@Conditional的动态装配java@Configuration @ConditionalOnClass(DataSource.class) // 当类路径存在DataSource时生效 public class DataSourceAutoConfiguration { @Bean public DataSource dataSource() { ... } } -
配置加载顺序 :
\\text{应用属性} \> \\text{命令行参数} \> \\text{SPI扩展}
2. 起步依赖(Starter)
- 依赖传递逻辑 :
\\text{spring-boot-starter-web} \\Rightarrow \\text{spring-webmvc} + \\text{tomcat} + \\text{jackson}
- 自定义Starter步骤 :
- 创建
META-INF/spring.factories - 声明自动配置类:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.MyAutoConfiguration
- 创建
3. 嵌入式容器
- Tomcat启动流程:
\\text{SpringApplication.run()} \\rightarrow \\text{TomcatServletWebServerFactory} \\rightarrow \\text{Server.start()}
三、Bean对象深度解析
1. IoC容器核心
-
Bean生命周期 :
graph LR A[实例化] --> B[属性注入] B --> C[初始化] C --> D[使用] D --> E[销毁] -
作用域对比 :
作用域 注解 特点 单例(Singleton) @Scope("singleton")容器内唯一实例 原型(Prototype) @Scope("prototype")每次请求创建新实例
2. 依赖注入方式
-
构造器注入 (推荐):
java@Service public class UserService { private final UserRepository repo; @Autowired public UserService(UserRepository repo) { // 构造器注入 this.repo = repo; } } -
注解对比 :
\\text{@Autowired} \\approx \\text{@Resource} \\quad \\text{(后者支持name指定)}
3. Bean的高级特性
-
延迟初始化 :
java@Lazy @Bean public HeavyResource heavyResource() { ... } // 首次使用时初始化 -
条件装配 :
java@Bean @ConditionalOnProperty(name="cache.enabled", havingValue="true") public CacheManager cacheManager() { ... }
四、进阶实践技巧
-
Bean生命周期干预
java@Bean(initMethod = "init", destroyMethod = "cleanup") public DataSource dataSource() { ... } -
解决Bean冲突
- 使用
@Qualifier("beanName")明确指定 - 主候选方案:
@Primary
- 使用
-
动态代理机制
- JDK动态代理:基于接口
$Proxy0 - CGLIB代理:生成子类
Enhancer.create()
- JDK动态代理:基于接口
五、调试与问题定位
-
查看Bean装配列表 :
bash# 启动时添加参数 java -jar app.jar --debug -
依赖树分析 :
bashmvn dependency:tree | grep conflict
通过此框架,你可逐步深入理解SpringBoot的自动化魔法及Bean管理的精髓。实践中建议结合源码调试(如AnnotationConfigApplicationContext),以强化认知。