Java 学习笔记 从零基础入门到精通实战指南(2025 最新更新版)

狐沐说

关注

阅读 9

06-22 12:00

Java学习笔记:从入门到精通(2025更新版)

一、Java基础(2025版)

1.1 开发环境配置

JDK推荐使用LTS版本17最新版本21,通过SDKMAN!进行多版本管理:

# 安装SDKMAN!
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"

# 安装并使用Java 21
sdk install java 21.0.1-tem
sdk use java 21.0.1-tem

IDE推荐使用IntelliJ IDEA 2025.1VS Code(需安装Extension Pack for Java)。

1.2 核心语法增强

1.2.1 文本块(Java 15+)
String html = """
    <html>
        <body>
            Hello, Java 21!
        </body>
    </html>
""";
1.2.2 模式匹配(Java 17+)
// 传统写法
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

// 模式匹配写法
if (obj instanceof String s) {
    System.out.println(s.length());
}
1.2.3 记录类(Java 16+)
// 传统类
class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Getters, equals, hashCode, toString
}

// 记录类
record Point(int x, int y) {}
1.2.4 增强的switch(Java 14+)
int day = 3;
String result = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> throw new IllegalArgumentException("Invalid day: " + day);
};

二、面向对象编程(2025版)

2.1 密封类(Java 17+)

// 限制继承范围
public sealed interface Shape 
    permits Circle, Rectangle, Square {
    double area();
}

final class Circle implements Shape { ... }
final class Rectangle implements Shape { ... }
non-sealed class Square implements Shape { ... }

2.2 接口增强

// Java 8+ 默认方法
public interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default implementation");
    }
    
    // Java 9+ 私有方法
    private void privateMethod() {
        System.out.println("Private implementation");
    }
}

三、Java进阶(2025版)

3.1 虚拟线程(Java 21+)

// 传统线程池写法
ExecutorService executor = Executors.newFixedThreadPool(200);
for (int i = 0; i < 1000; i++) {
    executor.submit(() -> {
        Thread.sleep(Duration.ofSeconds(1));
        return "Done";
    });
}

// 虚拟线程写法
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10000).forEach(i -> {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1));
            return "Done";
        });
    });
}

3.2 结构化并发(Java 21+)

// 并行执行多个任务
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<String> task1 = scope.fork(() -> fetchUser());
    Future<Integer> task2 = scope.fork(() -> fetchOrderCount());

    scope.join();           // 等待所有任务完成
    scope.throwIfFailed();  // 处理失败的任务

    String user = task1.resultNow();
    int count = task2.resultNow();
}

3.3 向量API(Java 21+)

// 传统数组计算
float[] a = new float[1024];
float[] b = new float[1024];
float[] c = new float[1024];

for (int i = 0; i < a.length; i++) {
    c[i] = a[i] * b[i] + 42.0f;
}

// 向量API加速计算
VectorSpecies<Float> species = FloatVector.SPECIES_PREFERRED;
for (int i = 0; i < a.length; i += species.length()) {
    var m = species.indexInRange(i, a.length);
    var va = FloatVector.fromArray(species, a, i, m);
    var vb = FloatVector.fromArray(species, b, i, m);
    var vc = va.mul(vb).add(42.0f);
    vc.intoArray(c, i, m);
}

四、实用类库与框架(2025版)

4.1 HTTP客户端(Java 11+)

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.example.com/data"))
            .header("Content-Type", "application/json")
            .GET()
            .build();

        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(System.out::println)
            .join();
    }
}

4.2 项目构建(Maven vs Gradle)

Gradle Kotlin DSL示例
// build.gradle.kts
plugins {
    application
    kotlin("jvm") version "1.9.20"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web:3.2.4")
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
}

application {
    mainClass.set("com.example.MainKt")
}

五、微服务与云原生(2025版)

5.1 Spring Boot 3.2+

// REST API示例
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "John Doe", "john@example.com");
    }

    record User(Long id, String name, String email) {}
}

5.2 容器化与Kubernetes

# Dockerfile示例
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY target/myapp.jar .
CMD ["java", "-jar", "myapp.jar"]

# Kubernetes部署示例
apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-service
  template:
    metadata:
      labels:
        app: user-service
    spec:
      containers:
      - name: user-service
        image: myregistry/user-service:1.0.0
        ports:
        - containerPort: 8080
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1024Mi"
            cpu: "500m"

六、响应式编程(2025版)

6.1 Reactor框架

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;

public class ReactiveExample {
    public static void main(String[] args) {
        // 创建数据流
        Flux<String> names = Flux.just("Alice", "Bob", "Charlie")
            .delayElements(Duration.ofMillis(500));

        // 转换与过滤
        Flux<String> filteredNames = names
            .filter(name -> name.length() > 4)
            .map(String::toUpperCase);

        // 订阅并消费
        filteredNames.subscribe(
            name -> System.out.println("Received: " + name),
            error -> System.err.println("Error: " + error),
            () -> System.out.println("Completed")
        );

        // 合并多个Mono
        Mono<String> mono1 = Mono.just("Hello");
        Mono<String> mono2 = Mono.just("World");
        
        Mono.zip(mono1, mono2)
            .map(tuple -> tuple.getT1() + " " + tuple.getT2())
            .subscribe(System.out::println);
    }
}

6.2 Spring WebFlux

// 响应式REST API
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("/products")
    public Flux<Product> getAllProducts() {
        return productService.findAll();
    }

    @GetMapping("/products/{id}")
    public Mono<Product> getProductById(@PathVariable String id) {
        return productService.findById(id);
    }
}

七、函数式编程(2025版)

7.1 Stream API增强

import java.util.List;
import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        List<String> words = List.of("hello", "world", "java", "stream");

        // 传统流操作
        words.stream()
            .filter(w -> w.length() > 4)
            .map(String::toUpperCase)
            .forEach(System.out::println);

        // 新的takeWhile/dropWhile方法
        Stream.of(1, 2, 3, 4, 5, 2, 1)
            .takeWhile(n -> n < 5)  // [1, 2, 3, 4]
            .forEach(System.out::print);

        Stream.of(1, 2, 3, 4, 5, 2, 1)
            .dropWhile(n -> n < 5)  // [5, 2, 1]
            .forEach(System.out::print);
    }
}

7.2 函数式接口与Lambda

// 自定义函数式接口
@FunctionalInterface
interface TriFunction<T, U, V, R> {
    R apply(T t, U u, V v);
}

// 使用示例
TriFunction<Integer, Integer, Integer, Integer> sum = (a, b, c) -> a + b + c;
int result = sum.apply(1, 2, 3); // 6

八、测试技术(2025版)

8.1 JUnit 5与Mockito

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    public void testGetUserById() {
        // 模拟存储库行为
        when(userRepository.findById(1L))
            .thenReturn(new User(1L, "John Doe", "john@example.com"));

        // 执行测试
        User result = userService.getUserById(1L);

        // 验证结果
        assertNotNull(result);
        assertEquals("John Doe", result.getName());
        verify(userRepository, times(1)).findById(1L);
    }
}

8.2 测试容器

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@Testcontainers
@SpringBootTest
public class DatabaseIntegrationTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }

    @Test
    void contextLoads() {
        // 测试数据库连接
    }
}

九、数据持久化(2025版)

9.1 Spring Data JPA 3.2+

// 实体类
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    // getters/setters
}

// 仓库接口
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByNameContaining(String name);

    @Query("SELECT p FROM Product p WHERE p.price > :minPrice")
    List<Product> findByPriceGreaterThan(double minPrice);
}

9.2 响应式数据访问(R2DBC)

// R2DBC响应式仓库
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import reactor.core.publisher.Flux;

public interface UserRepository extends ReactiveCrudRepository<User, Long> {
    Flux<User> findByLastName(String lastName);
}

// 使用示例
@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Flux<User> getUsersByLastName(String lastName) {
        return userRepository.findByLastName(lastName);
    }
}

十、实战项目:Todo应用(2025版)

10.1 项目架构

todo-app/
├── todo-backend/            # Spring Boot后端
│   ├── src/
│   │   ├── main/
│   │   │   ├── java/com/example/todo/
│   │   │   │   ├── controller/      # REST控制器
│   │   │   │   ├── service/         # 业务逻辑
│   │   │   │   ├── repository/      # 数据访问
│   │   │   │   ├── entity/          # 实体类
│   │   │   │   └── TodoApplication.java
│   │   │   └── resources/
│   │   │       ├── application.yml  # 配置文件
│   │   │       └── static/          # 静态资源
│   │   └── test/
│   │       └── java/com/example/todo/ # 测试类
│   └── pom.xml
└── todo-frontend/           # React前端
    ├── src/
    │   ├── components/      # React组件
    │   ├── services/        # API服务
    │   ├── App.jsx
    │   └── index.jsx
    └── package.json

10.2 后端核心代码

// Todo实体
@Entity
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private boolean completed;
    // getters/setters
}

// Todo控制器
@RestController
@RequestMapping("/api/todos")
public class TodoController {
    private final TodoService todoService;

    @GetMapping
    public List<Todo> getAllTodos() {
        return todoService.getAllTodos();
    }

    @PostMapping
    public Todo createTodo(@RequestBody Todo todo) {
        return todoService.createTodo(todo);
    }

    @PutMapping("/{id}")
    public Todo updateTodo(@PathVariable Long id, @RequestBody Todo todoDetails) {
        return todoService.updateTodo(id, todoDetails);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTodo(@PathVariable Long id) {
        todoService.deleteTodo(id);
        return ResponseEntity.ok().build();
    }
}

10.3 前端核心代码(React + Vite)

// TodoList组件
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const TodoList = () => {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');

  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    const response = await axios.get('/api/todos');
    setTodos(response.data);
  };

  const handleCreateTodo = async () => {
    if (!newTodo.trim()) return;
    await axios.post('/api/todos', { title: newTodo, completed: false });
    setNewTodo('');
    fetchTodos();
  };

  const handleToggleComplete = async (id, completed) => {
    await axios.put(`/api/todos/${id}`, { completed });
    fetchTodos();
  };

  return (
    <div className="container mx-auto p-4">
      Todo List
      
      <div className="flex mb-4">
        <input
          type="text"
          value={newTodo}
          onChange={(e) => setNewTodo(e.target.value)}
          className="flex-1 p-2 border rounded-l-md"
          placeholder="Add new todo"
        />
        <button
          onClick={handleCreateTodo}
          className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-r-md"
        >
          Add
        </button>
      </div>
      
      <ul className="space-y-2">
        {todos.map((todo) => (
          <li
            key={todo.id}
            className={`flex items-center p-2 ${
              todo.completed ? 'bg-gray-100 line-through' : 'bg-white'
            } rounded-md`}
          >
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => handleToggleComplete(todo.id, !todo.completed)}
              className="mr-2"
            />
            <span>{todo.title}</span>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TodoList;

以上代码示例涵盖了Java 21的最新特性、现代开发工具链以及微服务架构,帮助你快速掌握Java开发的核心技能。建议通过实际项目练习来加深理解,例如构建一个完整的Web应用或微服务系统。

Java 学习笔记,零基础入门,Java 精通实战,2025 更新版,Java 基础语法,面向对象编程,Java 核心类库,数据结构与算法,多线程编程,JVM 原理,JavaWeb 开发,Spring 框架,MyBatis 框架,项目实战,Java 面试技巧

代码获取方式 https://pan.quark.cn/s/14fcf913bae6

精彩评论(0)

0 0 举报