一、Spring 的纯注解配置(告别 XML)
✅ 核心思想 :用注解代替
applicationContext.xml
1️⃣ @Bean------ 注册对象到 IOC 容器
作用:
将一个对象放入 Spring 的 IOC 容器(等价于 <bean/>)
@Bean
public DataSource dataSource() {
return new DruidDataSource();
}
属性说明:
| 属性 | 作用 |
|---|---|
| value | 指定 Bean 在 IOC 容器中的 id |
✅ 默认方法名 = Bean 的 id
2️⃣ @PropertySource------ 加载 properties 文件
作用:
加载外部配置文件(等价于 <context:property-placeholder/>)
@PropertySource("classpath:db.properties")
属性说明:
| 属性 | 作用 |
|---|---|
| value | properties 文件路径 |
3️⃣ @ComponentScan------ 包扫描
作用:
指定 Spring 扫描哪些包(等价于 <context:component-scan/>)
@ComponentScan("com.hg")
✅ 常用包:
-
controller
-
service
-
mapper
4️⃣ @Import------ 导入其他配置类
作用:
引入其他 Java 配置类(等价于 <import/>)
@Import({MyBatisConfig.class, DataSourceConfig.class})
✅ 避免循环导入(⚠️ 易踩坑)
5️⃣ @Configuration------ 标识配置类
作用:
告诉 Spring:这是一个配置类 (等价于 applicationContext.xml)
@Configuration
public class SpringConfig {
}
✅ 必须配合 @ComponentScan/ @Bean使用
二、Spring Boot 入门(重点)
一、Spring Boot 是什么?
✅ Spring + Spring MVC 的"快速开发脚手架"
✅ 核心特点
| 特性 | 说明 |
|---|---|
| 无 XML | 几乎零配置 |
| 起步依赖 | starter 一键集成 |
| 内嵌容器 | 内置 Tomcat |
| 自动装配 | 约定优于配置 |
⚠️ 不是对 Spring 的增强,而是"更快的使用方式"
二、Spring Boot 入门案例(标准写法)
1️⃣ pom.xml配置
✅ ① 继承 Spring Boot 父工程
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/>
</parent>
✅ ② 添加 Web 启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2️⃣ Controller 示例
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping
public String hello() {
return "Hello Spring Boot!";
}
}
3️⃣ 启动类(⚠️ 极其重要)
package com.hg;
@SpringBootApplication
public class SpringbootHelloworldApp {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApp.class, args);
}
}
✅ 启动类必须放在 controller / service / mapper 的上级包
三、Spring Boot Starter(重点)
1️⃣ 什么是 Starter?
✅ Starter = 依赖 + 自动配置 + 默认配置
| 类型 | 说明 |
|---|---|
| 官方 starter | spring-boot-starter-xxx |
| 第三方 starter | xxx-spring-boot-starter |
2️⃣ 命名规范(面试常问)
✅ 官方 Starter
spring-boot-starter-web
spring-boot-starter-data-jpa
✅ 第三方 Starter
mybatis-spring-boot-starter
druid-spring-boot-starter
3️⃣ 常用 Starter 速查表
| 功能 | Starter |
|---|---|
| Web 开发 | spring-boot-starter-web |
| MyBatis | mybatis-spring-boot-starter |
| 测试 | spring-boot-starter-test |
| JDBC | spring-boot-starter-jdbc |
四、常见坑点总结(⚠️ 必看)
❌ 启动类位置错误
controller
service
mapper
↑
启动类必须在这里
❌ 忘记加 @SpringBootApplication
@SpringBootApplication // 缺一不可
❌ Starter 版本不匹配
✅ 建议统一使用父工程管理版本
五、总结(一句话记忆)
Spring 纯注解 = Java 配置 + 注解
Spring Boot = Starter + 自动装配 + 内嵌容器
📌 适合发布 CSDN 的理由
✅ 结构清晰
✅ 实战导向
✅ 适合新手
✅ 可直接复制运行
✅ 覆盖面试高频点
如果你愿意,我可以帮你:
-
✅ 改成 "保姆级图文教程"
-
✅ 加 运行截图
-
✅ 改成 面试问答版
-
✅ 或帮你写一篇 《SSM 转 Spring Boot 避坑指南》
直接告诉我你要哪种风格 👍