一、Spring Boot本质揭秘(厨房理论)
想象你要开一家餐厅:
- 传统Spring = 手工厨房
需要自己砌灶台(配置XML)、买锅具(导入jar包)、招厨师(Bean管理) - Spring Boot = 智能中央厨房
预制电磁灶(自动配置)、全套厨具套装(starter依赖)、AI厨师(条件装配)
二、5大核心功能拆解(附代码实战)
1. 自动装配(智能菜谱识别)
// 只需添加@SpringBootApplication
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args); // 自动加载所有厨具
}
}
2. 起步依赖(厨具全家桶)
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
3. 内嵌容器(便携电磁炉)
// 无需部署Tomcat,直接运行main方法启动
// 访问 http://localhost:8080
4. Actuator(厨房监控系统)
# application.yml
management:
endpoints:
web:
exposure:
include: "*" # 开启所有监控端点
endpoint:
health:
show-details: always
5. 外部化配置(万能调味台)
# 优先级从高到低
1. 命令行参数 --server.port=9090
2. application-{profile}.yml
3. application.yml
4. @PropertySource注解
三、实战:3小时开发电商系统
场景1:商品查询接口(15分钟)
@RestController
@RequestMapping("/products")
public class ProductController {
// 内存数据库
private static final Map DB = new HashMap<>();
static {
DB.put(1L, new Product(1L, "iPhone15", 6999));
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return DB.get(id); // 自动转JSON
}
}
场景2:集成MySQL数据库(30分钟)
@Entity
@Data // Lombok自动生成getter/setter
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private BigDecimal price;
}
public interface ProductRepository extends JpaRepository {
}
@Service
@RequiredArgsConstructor
public class ProductService {
private final ProductRepository productRepo;
public Product findById(Long id) {
return productRepo.findById(id).orElseThrow();
}
}
场景3:订单创建(事务控制)
@Transactional
public Order createOrder(Long productId, Integer quantity) {
Product product = productService.findById(productId);
// 扣减库存
product.setStock(product.getStock() - quantity);
productRepo.save(product);
// 生成订单
Order order = new Order();
order.setProductId(productId);
order.setAmount(product.getPrice().multiply(BigDecimal.valueOf(quantity)));
return orderRepo.save(order);
}
四、Spring Boot优势矩阵
传统Spring | Spring Boot |
需要配置web.xml | 零XML配置 |
手动管理依赖冲突 | starter自动版本控制 |
需外置Tomcat | 内嵌容器一键启动 |
开发效率低 | 快速原型开发 |
监控功能需集成 | Actuator开箱即用 |
五、避坑指南(血泪经验)
1.版本兼容问题
- Spring Boot 3.x需要Java 17+
- MySQL驱动包名已改为com.mysql.cj.jdbc.Driver
2.端口冲突
server:
port: 8080 # 默认端口,冲突时可修改
3.自动配置失效
- 检查主类是否在根包下
- 确认没有使用错误的@ComponentScan
4.跨域问题
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
六、性能调优速查表
- JVM参数优化
- java -jar -Xms512m -Xmx1024m myapp.jar
- Tomcat线程池配置
- server:
- tomcat:
- max-threads: 200
- min-spare-threads: 10
- 数据库连接池
- spring:
- datasource:
- hikari:
- maximum-pool-size: 20
- connection-timeout: 30000
按照这个指南实践,你将在3天内掌握Spring Boot核心开发能力,达到中级Java工程师水平!
如果您觉得不错,麻烦给个三连支持一下,谢谢。
Tags:propertysource