以下是为有Java基础的学习者设计的Spring Boot学习大纲,结合现代开发实践和关键示例:
1. Spring Boot核心概念
// 最小化启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 配置文件管理
# application-dev.yml
server:
port: 8081
logging:
level:
root: DEBUG
3. 第一个REST API
@RestController
@RequestMapping("/api/demo")
public class DemoController {
@Value("${app.version}") // 注入配置
private String version;
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return ResponseEntity.ok("Spring Boot " + version);
}
}
1. Spring Data JPA
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
// getters/setters
}
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByUsernameContaining(String keyword); // 自动生成查询
}
2. 事务管理
@Service
@Transactional
public class UserService {
public User createUser(User user) {
// 事务操作
}
}
3. 整合MyBatis
<!-- pom.xml依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
1. RESTful API设计
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(...);
}
}
2. 参数校验
public class CreateUserRequest {
@NotBlank
@Size(min = 5, max = 20)
private String username;
@Email
private String email;
}
@PostMapping("/users")
public User createUser(@Valid @RequestBody CreateUserRequest request) {
// ...
}
3. 文件上传/下载
@PostMapping("/upload")
public String handleUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
file.transferTo(new File("/uploads/" + file.getOriginalFilename()));
}
return "redirect:/";
}
1. 安全控制
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(withDefaults());
return http.build();
}
}
2. 缓存管理
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
// 数据库查询
}
}
3. 消息队列
@RabbitListener(queues = "orderQueue")
public void processOrder(Order order) {
// 处理订单逻辑
}
1. Actuator监控
management:
endpoints:
web:
exposure:
include: health,info,metrics
endpoint:
health:
show-details: always
2. 单元测试
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("Alice"));
}
}
3. Docker部署
FROM eclipse-temurin:17-jdk
VOLUME /tmp
COPY target/*.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
电商平台核心模块示例
关键技术组合:
// 使用Spring Cloud OpenFeign调用外部API
@FeignClient(name = "payment-service", url = "${payment.service.url}")
public interface PaymentClient {
@PostMapping("/payments")
PaymentResponse createPayment(@RequestBody PaymentRequest request);
}
// 使用WebSocket实现实时通知
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
通过这个大纲,可以在4-6周内系统掌握Spring Boot开发,建议配合实际项目边学边做,重点理解"约定优于配置"的设计理念。