Java从零到熟练(十一):Spring框架入门

Spring是Java企业级开发的事实标准,掌握Spring就是掌握现代Java开发。

目录

  • [1. Spring概述](#1. Spring概述)
  • [2. Spring Boot快速入门](#2. Spring Boot快速入门)
  • [3. 依赖注入(DI)](#3. 依赖注入(DI))
  • [4. Spring AOP](#4. Spring AOP)
  • [5. Spring Data JPA](#5. Spring Data JPA)
  • [6. 总结](#6. 总结)
  • 参考资源

1. Spring概述

1.1 什么是Spring?

Spring是一个轻量级的控制反转(IoC)和面向切面编程(AOP)的容器框架。

Spring的核心特性:

  • IoC(控制反转):对象创建和依赖管理由容器负责
  • DI(依赖注入):通过构造函数、setter或字段注入依赖
  • AOP(面向切面编程):在不修改代码的情况下增强功能
  • MVC:Web应用开发框架
  • 事务管理:声明式事务管理

1.2 Spring生态

复制代码
Spring生态系统
├── Spring Framework(核心框架)
├── Spring Boot(快速开发)
├── Spring Cloud(微服务)
├── Spring Data(数据访问)
├── Spring Security(安全)
└── Spring Batch(批处理)

2. Spring Boot快速入门

2.1 创建Spring Boot项目

方式一:Spring Initializr

  1. 访问 https://start.spring.io/
  2. 选择项目类型(Maven/Gradle)
  3. 填写项目信息
  4. 选择依赖
  5. 生成项目

2.2 第一个Spring Boot应用

java 复制代码
// 主应用类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
java 复制代码
// 控制器类
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
    
    @GetMapping("/hello/{name}")
    public String helloName(String name) {
        return "Hello, " + name + "!";
    }
}
xml 复制代码
<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2.3 运行应用

bash 复制代码
# 方式一:Maven
mvn spring-boot:run

# 方式二:打包后运行
mvn package
java -jar target/myapp-0.0.1-SNAPSHOT.jar

3. 依赖注入(DI)

3.1 什么是依赖注入?

依赖注入是IoC的实现方式,对象不自己创建依赖,而是由容器注入。

java 复制代码
// 没有依赖注入
public class UserService {
    private UserRepository repository = new UserRepository();  // 硬编码
}

// 使用依赖注入
@Service
public class UserService {
    private final UserRepository repository;
    
    // 构造函数注入(推荐)
    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}

3.2 注入方式

java 复制代码
// 1. 构造函数注入(推荐)
@Service
public class UserService {
    private final UserRepository repository;
    
    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}

// 2. Setter注入
@Service
public class UserService {
    private UserRepository repository;
    
    @Autowired
    public void setRepository(UserRepository repository) {
        this.repository = repository;
    }
}

// 3. 字段注入(不推荐)
@Service
public class UserService {
    @Autowired
    private UserRepository repository;
}

3.3 Bean管理

java 复制代码
// 定义Bean
@Service
public class UserService {
    // Spring会自动管理这个类的实例
}

@Repository
public class UserRepository {
    // 数据访问层Bean
}

@Component
public class MyComponent {
    // 通用组件Bean
}

// 配置类
@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

4. Spring AOP

4.1 什么是AOP?

面向切面编程(AOP)可以在不修改原有代码的情况下增加新功能。

java 复制代码
// 切面类
@Aspect
@Component
public class LogAspect {
    
    @Before("execution(* com.example.service.*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        System.out.println("方法执行前:" + joinPoint.getSignature().getName());
    }
    
    @After("execution(* com.example.service.*.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        System.out.println("方法执行后:" + joinPoint.getSignature().getName());
    }
    
    @Around("execution(* com.example.service.*.*(..))")
    public Object aroundMethod(JoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        
        Object result = joinPoint.proceed();
        
        long end = System.currentTimeMillis();
        System.out.println("方法耗时:" + (end - start) + "ms");
        
        return result;
    }
}

5. Spring Data JPA

5.1 实体类

java 复制代码
import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, length = 50)
    private String name;
    
    @Column(nullable = false, unique = true)
    private String email;
    
    @Column(name = "created_at")
    private LocalDateTime createdAt;
    
    // 构造函数
    public User() {}
    
    public User(String name, String email) {
        this.name = name;
        this.email = email;
        this.createdAt = LocalDateTime.now();
    }
    
    // Getters and Setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}

5.2 Repository接口

java 复制代码
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    // 方法名查询
    List<User> findByName(String name);
    List<User> findByEmailContaining(String email);
    Optional<User> findByEmail(String email);
    
    // JPQL查询
    @Query("SELECT u FROM User u WHERE u.name LIKE %:keyword% OR u.email LIKE %:keyword%")
    List<User> searchByKeyword(String keyword);
    
    // 原生SQL查询
    @Query(value = "SELECT * FROM users WHERE created_at > :date", nativeQuery = true)
    List<User> findRecentUsers(LocalDateTime date);
}

5.3 Service层

java 复制代码
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    
    private final UserRepository userRepository;
    
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }
    
    public User createUser(User user) {
        return userRepository.save(user);
    }
    
    public User updateUser(Long id, User userDetails) {
        User user = userRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("User not found"));
        
        user.setName(userDetails.getName());
        user.setEmail(userDetails.getEmail());
        
        return userRepository.save(user);
    }
    
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

5.4 Controller层

java 复制代码
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    private final UserService userService;
    
    public UserController(UserService userService) {
        this.userService = userService;
    }
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return ResponseEntity.ok(userService.updateUser(id, user));
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ResponseEntity.noContent().build();
    }
}

6. 总结

本篇我们学习了:

Spring Boot :快速创建应用、自动配置

依赖注入 :构造函数注入、Setter注入、字段注入

AOP :面向切面编程、切面定义

Spring Data JPA :实体、Repository、查询方法

RESTful API:控制器、请求映射、响应处理

核心要点:

  1. Spring Boot简化了Spring应用的创建和配置
  2. 依赖注入是Spring的核心,推荐使用构造函数注入
  3. AOP可以在不修改代码的情况下增加功能
  4. Spring Data JPA简化了数据访问层的开发

下一篇预告: 《Java从零到熟练(十二):Java与AI工具整合》

  • 学习如何用Java调用AI API
  • 了解LangChain4j框架
  • 掌握AI辅助开发技巧

参考资源

  1. Spring官方文档
  2. Spring Boot官方指南
  3. Spring Data JPA文档

下一篇: Java从零到熟练(十二):Java与AI工具整合

相关推荐
小锋java12341 小时前
【技术专题】LangChain4j 开发Java Agent智能体 - 整合SpringBoot4
java·人工智能
十五年专注C++开发1 小时前
cereal 库:C++ 序列化的轻量之选
开发语言·c++·序列化·反序列化·cereal
星卯教育tony1 小时前
2026年全国青少年信息素养大赛主题应用 数字守艺人 丝路新城 星火征程 智传民韵 c++ python scratch 所有真题免费分享
开发语言·c++
飞翔中文网2 小时前
Java学习笔记之抽象类
java·笔记·学习
z落落2 小时前
C# 继承:父子构造函数 + base 关键字 +五大访问修饰符(同项目+跨项目 全覆盖)
开发语言·c#
海盗12342 小时前
C#中PDF操作-QuestPDF页面设置与布局
java·pdf·c#
day day day ...2 小时前
MyBatis / MyBatis-Plus 动态 SQL 中 OGNL 表达式的常见陷阱与源码分析
java·开发语言·mybatis
basketball6162 小时前
C++ bitset 头文件完全指南
开发语言·c++
Kiling_07042 小时前
Java IO流:字节流实战与性能优化
java·开发语言·php