Java开发秘籍:从入门到精通的50个实用代码示例

602 阅读13分钟

大家好,欢迎来到 非鱼牛马社 🐴🐟

这里是一个不那么“正经”,但非常实用的技术栖息地。我们不追热点、不卷八股,但我们 热爱代码、享受拆解、坚持分享

在这个内容里,我会用最接地气的方式,带你搞懂 Java、Vue、Spring Boot、MySQL 等开发中的真问题真解决方案。不整花活、不兜圈子,每一行代码都可能是我深夜踩坑后的血泪总结

如果你也是一个在代码世界摸爬滚打的“牛马”,那咱就是一家人。


🎯 今天搞啥?

我们来分享一个知识:🚀 Java开发秘籍:从入门到精通的50个实用代码示例


Java 常用代码大全(第一部分)

目录

  1. 基础操作
  2. 字符串处理
  3. 日期时间
  4. 集合操作

基础操作

1. 基本数据类型转换

// 字符串转整数
String str = "123";
int num1 = Integer.parseInt(str);
Integer num2 = Integer.valueOf(str);

// 整数转字符串
int number = 123;
String str1 = String.valueOf(number);
String str2 = Integer.toString(number);

// 字符串转浮点数
String str3 = "123.45";
double d1 = Double.parseDouble(str3);
Double d2 = Double.valueOf(str3);

2. 随机数生成

// 生成随机整数
Random random = new Random();
int randomNum = random.nextInt(100); // 0-99之间的随机数

// 生成指定范围的随机数
int min = 10;
int max = 50;
int randomInRange = random.nextInt(max - min + 1) + min;

// 生成随机浮点数
double randomDouble = random.nextDouble(); // 0.0-1.0之间的随机数

字符串处理

3. 字符串判空

public boolean isEmptyString(String str) {
    // 判断字符串是否为空
    return str == null || str.trim().isEmpty();
}

4. 字符串分割与合并

// 字符串分割
String text = "apple,banana,orange";
String[] fruits = text.split(",");

// 字符串合并
String[] words = {"Hello""World"};
String joined1 = String.join(" ", words);
String joined2 = Arrays.stream(words).collect(Collectors.joining(" "));

5. 字符串格式化

// 使用 String.format
String name = "John";
int age = 30;
String formatted = String.format("Name: %s, Age: %d", name, age);

// 使用 MessageFormat
String pattern = "Name: {0}, Age: {1}";
String formatted2 = MessageFormat.format(pattern, name, age);

6. 字符串查找和替换

String text = "Hello World";
// 查找子串
boolean contains = text.contains("World");
int index = text.indexOf("World");

// 替换字符串
String replaced = text.replace("World""Java");
String replacedRegex = text.replaceAll("\s+""-");

日期时间

7. 日期格式化

// 使用 LocalDateTime
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);

// 字符串转日期
String dateStr = "2024-03-20 10:30:00";
LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter);

8. 日期计算

LocalDate today = LocalDate.now();
// 增加天数
LocalDate futureDate = today.plusDays(7);
// 减少月份
LocalDate pastDate = today.minusMonths(1);
// 计算两个日期之间的天数
long daysBetween = ChronoUnit.DAYS.between(pastDate, today);

集合操作

9. List 操作

// 创建和初始化 List
List<String> list = new ArrayList<>();
List<String> list2 = Arrays.asList("a""b""c");
List<String> list3 = new ArrayList<>(Arrays.asList("a""b""c"));

// List 排序
Collections.sort(list);
list.sort(Comparator.naturalOrder());

// List 过滤
List<String> filtered = list.stream()
    .filter(item -> item.startsWith("a"))
    .collect(Collectors.toList());

10. Map 操作

// 创建和初始化 Map
Map<String, Integer> map = new HashMap<>();
map.put("apple"1);
map.put("banana"2);

// 安全获取值
Integer value = map.getOrDefault("orange"0);

// 遍历 Map
map.forEach((key, val) -> System.out.println(key + ": " + val));

// Map 转换为 List
List<String> keys = new ArrayList<>(map.keySet());
List<Integer> values = new ArrayList<>(map.values());

Java 常用代码大全(第二部分)

目录

  1. 文件操作
  2. IO 流操作
  3. 异常处理
  4. 多线程

文件操作

11. 文件读写

// 读取文件内容
public static String readFile(String filePath) throws IOException {
    return new String(Files.readAllBytes(Paths.get(filePath)));
}

// 写入文件内容
public static void writeFile(String filePath, String content) throws IOException {
    Files.write(Paths.get(filePath), content.getBytes());
}

// 按行读取文件
public static List<StringreadLines(String filePath) throws IOException {
    return Files.readAllLines(Paths.get(filePath));
}

12. 文件操作

// 创建目录
public static void createDirectory(String dirPath) throws IOException {
    Files.createDirectories(Paths.get(dirPath));
}

// 复制文件
public static void copyFile(String sourcePath, String targetPath) throws IOException {
    Files.copy(Paths.get(sourcePath), Paths.get(targetPath), 
               StandardCopyOption.REPLACE_EXISTING);
}

// 删除文件
public static void deleteFile(String filePath) throws IOException {
    Files.deleteIfExists(Paths.get(filePath));
}

IO 流操作

13. 缓冲流读写

// 使用缓冲流读取文件
public static String readWithBuffer(String filePath) {
    StringBuilder content = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append("\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content.toString();
}

// 使用缓冲流写入文件
public static void writeWithBuffer(String filePath, String content) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
        writer.write(content);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

14. 资源流处理

// 读取资源文件
public static String readResource(String resourcePath) {
    try (InputStream is = Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream(resourcePath)) {
        if (is == nullreturn null;
        return new String(is.readAllBytes());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

异常处理

15. 自定义异常

public class BusinessException extends RuntimeException {
    private String errorCode;
    
    public BusinessException(String message) {
        super(message);
    }
    
    public BusinessException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
}

16. 异常处理工具

public class ExceptionUtils {
    // 获取完整异常栈信息
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }
    
    // 安全执行方法
    public static <T> T executeWithRetry(Supplier<T> supplier, int maxRetries) {
        int retryCount = 0;
        while (retryCount < maxRetries) {
            try {
                return supplier.get();
            } catch (Exception e) {
                retryCount++;
                if (retryCount == maxRetries) {
                    throw e;
                }
            }
        }
        return null;
    }
}

多线程

17. 线程池创建

// 创建固定大小的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

// 创建缓存线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

// 创建定时任务线程池
ScheduledExecutorService scheduledThreadPool = 
    Executors.newScheduledThreadPool(5);

18. 异步任务处理

// 异步执行任务
public static <T> CompletableFuture<T> asyncExecute(Supplier<T> supplier) {
    return CompletableFuture.supplyAsync(supplier);
}

// 组合多个异步任务
public static void combineTasks() {
    CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
    CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
    
    CompletableFuture.allOf(future1, future2)
        .thenAccept(v -> {
            String result = future1.join() + " " + future2.join();
            System.out.println(result);
        });
}

19. 线程安全集合

// 线程安全的 List
List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
List<String> concurrentList = new CopyOnWriteArrayList<>();

// 线程安全的 Map
Map<StringString> concurrentMap = new ConcurrentHashMap<>();

// 线程安全的 Set
Set<String> concurrentSet = new CopyOnWriteArraySet<>();

20. 线程同步工具

public class ThreadSyncExample {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    
    public void doSyncTask() {
        lock.lock();
        try {
            // 执行同步操作
        } finally {
            lock.unlock();
        }
    }
    
    public void waitForSignal() throws InterruptedException {
        lock.lock();
        try {
            condition.await();
        } finally {
            lock.unlock();
        }
    }
    
    public void sendSignal() {
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
}

Java 常用代码大全(第三部分)

目录

  1. 常用工具类
  2. 设计模式
  3. 网络编程
  4. 数据库操作

常用工具类

21. JSON 处理(使用 Jackson)

public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();
    
    // 对象转 JSON 字符串
    public static String toJson(Object obj) throws JsonProcessingException {
        return mapper.writeValueAsString(obj);
    }
    
    // JSON 字符串转对象
    public static <T> T fromJson(String json, Class<T> clazz) 
            throws JsonProcessingException {
        return mapper.readValue(json, clazz);
    }
    
    // JSON 字符串转List
    public static <T> List<T> fromJsonList(String json, Class<T> clazz) 
            throws JsonProcessingException {
        JavaType type = mapper.getTypeFactory()
            .constructCollectionType(List.class, clazz);
        return mapper.readValue(json, type);
    }
}

22. 加密工具类

public class EncryptUtils {
    // MD5 加密
    public static String md5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(text.getBytes());
            return bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    
    // SHA-256 加密
    public static String sha256(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md.digest(text.getBytes());
            return bytesToHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

23. 验证工具类

public class ValidateUtils {
    // 邮箱验证
    public static boolean isValidEmail(String email) {
        String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
        return Pattern.matches(regex, email);
    }
    
    // 手机号验证(中国大陆)
    public static boolean isValidPhone(String phone) {
        String regex = "^1[3-9]\d{9}$";
        return Pattern.matches(regex, phone);
    }
    
    // 身份证号验证
    public static boolean isValidIdCard(String idCard) {
        String regex = "(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)";
        return Pattern.matches(regex, idCard);
    }
}

设计模式

24. 单例模式

// 双重检查锁定实现单例
public class Singleton {
    private volatile static Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// 枚举实现单例
public enum SingletonEnum {
    INSTANCE;
    
    public void doSomething() {
        // 具体实现
    }
}

25. 工厂模式

// 简单工厂
public class SimpleFactory {
    public static Product createProduct(String type) {
        switch (type) {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new IllegalArgumentException("Unknown product type");
        }
    }
}

// 工厂方法
interface Factory {
    Product createProduct();
}

class ProductAFactory implements Factory {
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}

26. 建造者模式

public class User {
    private final String name;
    private final int age;
    private final String address;
    
    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.address = builder.address;
    }
    
    public static class Builder {
        private String name;
        private int age;
        private String address;
        
        public Builder name(String name) {
            this.name = name;
            return this;
        }
        
        public Builder age(int age) {
            this.age = age;
            return this;
        }
        
        public Builder address(String address) {
            this.address = address;
            return this;
        }
        
        public User build() {
            return new User(this);
        }
    }
}

网络编程

27. HTTP 请求(使用 HttpClient)

public class HttpUtils {
    private static final CloseableHttpClient httpClient = 
        HttpClients.createDefault();
        
    // GET 请求
    public static String doGet(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            return EntityUtils.toString(response.getEntity());
        }
    }
    
    // POST 请求
    public static String doPost(String url, Map<String, String> params) 
            throws IOException {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> parameters = new ArrayList<>();
        params.forEach((key, value) -> 
            parameters.add(new BasicNameValuePair(key, value)));
        httpPost.setEntity(new UrlEncodedFormEntity(parameters));
        
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            return EntityUtils.toString(response.getEntity());
        }
    }
}

28. WebSocket 客户端

@ClientEndpoint
public class WebSocketClient {
    private Session session;
    
    public void connect(String uri) throws Exception {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(thisnew URI(uri));
    }
    
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }
    
    @OnMessage
    public void onMessage(String message) {
        // 处理接收到的消息
    }
    
    public void sendMessage(String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }
}

数据库操作

29. JDBC 工具类

public class JdbcUtils {
    private static final String URL = "jdbc:mysql://localhost:3306/dbname";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
    
    public static void closeResources(Connection conn, Statement stmt, 
            ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

30. 数据库操作模板

public class DatabaseTemplate {
    // 查询单个对象
    public <T> T queryForObject(String sql, RowMapper<T> rowMapper, 
            Object... params) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }
            rs = stmt.executeQuery();
            if (rs.next()) {
                return rowMapper.mapRow(rs);
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.closeResources(conn, stmt, rs);
        }
    }
    
    // 查询列表
    public <T> List<T> queryForList(String sql, RowMapper<T> rowMapper, 
            Object... params) {
        List<T> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                stmt.setObject(i + 1, params[i]);
            }
            rs = stmt.executeQuery();
            while (rs.next()) {
                list.add(rowMapper.mapRow(rs));
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.closeResources(conn, stmt, rs);
        }
    }
}

@FunctionalInterface
interface RowMapper<T> {
    T mapRow(ResultSet rs) throws SQLException;
}

Java 常用代码大全(第四部分)

目录

  1. Lambda 表达式
  2. Stream API
  3. Optional 类
  4. 并发编程

Lambda 表达式

31. 常用 Lambda 表达式

// 列表排序
list.sort((a, b) -> a.compareTo(b));

// 过滤
List<String> filtered = list.stream()
    .filter(s -> s.length() > 5)
    .collect(Collectors.toList());

// 映射转换
List<Integer> lengths = list.stream()
    .map(String::length)
    .collect(Collectors.toList());

// 遍历
list.forEach(item -> System.out.println(item));

32. 函数式接口

// 自定义函数式接口
@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

// 使用函数式接口
public class LambdaExample {
    public void demo() {
        Calculator add = (a, b) -> a + b;
        Calculator subtract = (a, b) -> a - b;
        Calculator multiply = (a, b) -> a * b;
        
        System.out.println(add.calculate(53));      // 8
        System.out.println(subtract.calculate(53)); // 2
        System.out.println(multiply.calculate(53)); // 15
    }
}

Stream API

33. 集合转换

public class StreamExample {
    // List 转 Map
    public static <T> Map<String, T> listToMap(List<T> list, 
            Function<T, String> keyMapper) {
        return list.stream()
            .collect(Collectors.toMap(keyMapper, Function.identity()));
    }
    
    // 分组
    public static <T> Map<StringList<T>> groupBy(List<T> list, 
            Function<T, String> classifier) {
        return list.stream()
            .collect(Collectors.groupingBy(classifier));
    }
    
    // 去重
    public static <T> List<T> distinct(List<T> list) {
        return list.stream()
            .distinct()
            .collect(Collectors.toList());
    }
}

34. 数值流操作

public class NumberStreamExample {
    // 求和
    public static int sum(List<Integer> numbers) {
        return numbers.stream()
            .mapToInt(Integer::intValue)
            .sum();
    }
    
    // 平均值
    public static OptionalDouble average(List<Integer> numbers) {
        return numbers.stream()
            .mapToInt(Integer::intValue)
            .average();
    }
    
    // 最大值
    public static Optional<Integer> max(List<Integer> numbers) {
        return numbers.stream()
            .max(Integer::compareTo);
    }
}

35. 并行流

public class ParallelStreamExample {
    // 并行处理大量数据
    public static <T> List<T> parallelProcess(List<T> list, 
            Function<T, T> processor) {
        return list.parallelStream()
            .map(processor)
            .collect(Collectors.toList());
    }
    
    // 并行求和
    public static long parallelSum(List<Integer> numbers) {
        return numbers.parallelStream()
            .mapToLong(Integer::longValue)
            .sum();
    }
}

Optional 类

36. Optional 使用示例

public class OptionalExample {
    // 安全获取值
    public static String getValueSafely(Optional<String> optional) {
        return optional.orElse("default");
    }
    
    // 条件执行
    public static void executeIfPresent(Optional<String> optional, 
            Consumer<String> consumer) {
        optional.ifPresent(consumer);
    }
    
    // 链式调用
    public static String getChainedValue(Optional<User> userOptional) {
        return userOptional
            .map(User::getAddress)
            .map(Address::getCity)
            .map(City::getName)
            .orElse("Unknown");
    }
}

37. Optional 工具类

public class OptionalUtils {
    // 将可能为 null 的值转换为 Optional
    public static <T> Optional<T> toOptional(T value) {
        return Optional.ofNullable(value);
    }
    
    // 安全地获取嵌套对象的属性
    public static <TR> Optional<R> getNestedValue(T obj, 
            Function<TR> mapper) {
        return Optional.ofNullable(obj)
            .map(mapper);
    }
    
    // 组合多个 Optional
    public static <TUR> Optional<R> combine(Optional<T> opt1, 
            Optional<U> opt2, BiFunction<TUR> combiner) {
        return opt1.flatMap(t -> 
            opt2.map(u -> combiner.apply(t, u)));
    }
}

并发编程

38. CompletableFuture 示例

public class CompletableFutureExample {
    // 异步执行任务
    public static <T> CompletableFuture<T> asyncExecute(
            Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier);
    }
    
    // 组合多个异步任务
    public static <TUR> CompletableFuture<R> combine(
            CompletableFuture<T> future1,
            CompletableFuture<U> future2,
            BiFunction<TUR> combiner) {
        return future1.thenCombine(future2, combiner);
    }
    
    // 处理异步任务异常
    public static <T> CompletableFuture<T> handleAsync(
            Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier)
            .exceptionally(throwable -> {
                // 处理异常
                return null;
            });
    }
}

39. 线程池工具类

public class ThreadPoolUtils {
    private static final int CORE_POOL_SIZE = 
        Runtime.getRuntime().availableProcessors();
    private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
    private static final long KEEP_ALIVE_TIME = 60L;
    
    // 创建自定义线程池
    public static ExecutorService newThreadPool() {
        return new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
    
    // 优雅关闭线程池
    public static void shutdownPool(ExecutorService pool) {
        pool.shutdown();
        try {
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow();
            }
        } catch (InterruptedException e) {
            pool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

40. 并发集合工具类

public class ConcurrentCollectionUtils {
    // 创建线程安全的 Map
    public static <K, V> Map<KVcreateConcurrentMap() {
        return new ConcurrentHashMap<>();
    }
    
    // 创建线程安全的 List
    public static <T> List<TcreateConcurrentList() {
        return new CopyOnWriteArrayList<>();
    }
    
    // 创建线程安全的 Set
    public static <T> Set<TcreateConcurrentSet() {
        return new CopyOnWriteArraySet<>();
    }
    
    // 创建线程安全的队列
    public static <T> Queue<TcreateConcurrentQueue() {
        return new ConcurrentLinkedQueue<>();
    }
}

Java 常用代码大全(第五部分)

目录

  1. 测试相关
  2. 日志处理
  3. 性能优化
  4. 最佳实践

测试相关

41. JUnit 测试示例

@Test
public class UserServiceTest {
    private UserService userService;
    
    @Before
    public void setup() {
        userService = new UserService();
    }
    
    @Test
    public void testCreateUser() {
        User user = new User("John""john@example.com");
        User created = userService.createUser(user);
        
        assertNotNull(created);
        assertEquals("John", created.getName());
        assertEquals("john@example.com", created.getEmail());
    }
    
    @Test(expected = IllegalArgumentException.class)
    public void testCreateUserWithInvalidEmail() {
        User user = new User("John""invalid-email");
        userService.createUser(user);
    }
}

42. Mock 测试示例(使用 Mockito)

@RunWith(MockitoJUnitRunner.class)
public class OrderServiceTest {
    @Mock
    private UserRepository userRepository;
    
    @Mock
    private PaymentService paymentService;
    
    @InjectMocks
    private OrderService orderService;
    
    @Test
    public void testCreateOrder() {
        // 准备测试数据
        User user = new User("1""John");
        Order order = new Order("1""Product A"100.0);
        
        // 设置 Mock 行为
        when(userRepository.findById("1")).thenReturn(Optional.of(user));
        when(paymentService.processPayment(any())).thenReturn(true);
        
        // 执行测试
        OrderResult result = orderService.createOrder("1", order);
        
        // 验证结果
        assertTrue(result.isSuccess());
        verify(paymentService, times(1)).processPayment(any());
    }
}

日志处理

43. 日志配置(使用 SLF4J + Logback)

public class LogConfig {
    // 获取日志记录器
    private static final Logger logger = 
        LoggerFactory.getLogger(LogConfig.class);
    
    // 日志记录示例
    public void logExample() {
        logger.debug("Debug message");
        logger.info("Info message");
        logger.warn("Warning message");
        logger.error("Error message");
        
        // 带参数的日志
        String name = "John";
        logger.info("User {} logged in", name);
        
        // 带异常的日志
        try {
            // 可能抛出异常的代码
        } catch (Exception e) {
            logger.error("Error occurred", e);
        }
    }
}

44. 日志工具类

public class LogUtils {
    private static final Logger logger = 
        LoggerFactory.getLogger(LogUtils.class);
    
    // 记录方法执行时间
    public static <T> logExecutionTime(String methodName, 
            Supplier<T> supplier) {
        long startTime = System.currentTimeMillis();
        try {
            return supplier.get();
        } finally {
            long endTime = System.currentTimeMillis();
            logger.info("{} executed in {} ms", methodName, 
                (endTime - startTime));
        }
    }
    
    // 记录方法调用参数
    public static void logMethodCall(String methodName, Object... args) {
        logger.debug("Method {} called with args: {}", methodName, 
            Arrays.toString(args));
    }
}

性能优化

45. 缓存工具(使用 Guava Cache)

public class CacheUtils {
    private static final Cache<StringObject> cache = 
        CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10TimeUnit.MINUTES)
            .build();
    
    // 获取缓存值
    public static Object get(String key) {
        return cache.getIfPresent(key);
    }
    
    // 设置缓存值
    public static void put(String key, Object value) {
        cache.put(key, value);
    }
    
    // 获取值,如果不存在则计算
    public static Object getOrCompute(String key, 
            Callable<Object> valueLoader) {
        try {
            return cache.get(key, valueLoader);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

46. 性能监控工具

public class PerformanceMonitor {
    private static final Map<String, Long> startTimes = 
        new ConcurrentHashMap<>();
    private static final Map<String, List<Long>> executionTimes = 
        new ConcurrentHashMap<>();
    
    // 开始监控
    public static void start(String operationName) {
        startTimes.put(operationName, System.nanoTime());
    }
    
    // 结束监控
    public static void end(String operationName) {
        Long startTime = startTimes.remove(operationName);
        if (startTime != null) {
            long duration = System.nanoTime() - startTime;
            executionTimes.computeIfAbsent(operationName, 
                k -> new ArrayList<>()).add(duration);
        }
    }
    
    // 获取统计信息
    public static Map<String, PerformanceStats> getStats() {
        Map<String, PerformanceStats> stats = new HashMap<>();
        executionTimes.forEach((operation, times) -> {
            DoubleSummaryStatistics summary = 
                times.stream()
                    .mapToDouble(t -> t / 1_000_000.0// 转换为毫秒
                    .summaryStatistics();
            stats.put(operation, new PerformanceStats(
                summary.getCount(),
                summary.getAverage(),
                summary.getMin(),
                summary.getMax()
            ));
        });
        return stats;
    }
}

public class PerformanceStats {
    private final long count;
    private final double avgTime;
    private final double minTime;
    private final double maxTime;
    
    // 构造函数和 getter 方法
}

最佳实践

47. 参数验证工具

public class ValidationUtils {
    // 验证非空
    public static <T> requireNonNull(T obj, String message) {
        if (obj == null) {
            throw new IllegalArgumentException(message);
        }
        return obj;
    }
    
    // 验证字符串
    public static String requireNonEmpty(String str, String message) {
        if (str == null || str.trim().isEmpty()) {
            throw new IllegalArgumentException(message);
        }
        return str;
    }
    
    // 验证范围
    public static int requireRange(int value, int min, int max, 
            String message) {
        if (value < min || value > max) {
            throw new IllegalArgumentException(message);
        }
        return value;
    }
}

48. 通用响应封装

@Data
@AllArgsConstructor
public class Response<T> {
    private boolean success;
    private String message;
    private T data;
    private String errorCode;
    
    // 成功响应
    public static <T> Response<T> success(T data) {
        return new Response<>(true"Success", data, null);
    }
    
    // 失败响应
    public static <T> Response<T> error(String message) {
        return new Response<>(false, message, null"500");
    }
    
    // 自定义错误响应
    public static <T> Response<T> error(String message, 
            String errorCode) {
        return new Response<>(false, message, null, errorCode);
    }
}

49. 异常处理最佳实践

public class ExceptionHandling {
    // 统一异常处理
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Response<Void>> handleException(
            Exception ex) {
        logger.error("Unexpected error", ex);
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(Response.error("Internal server error"));
    }
    
    // 业务异常处理
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Response<Void>> handleBusinessException(
            BusinessException ex) {
        logger.warn("Business error: {}", ex.getMessage());
        return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .body(Response.error(ex.getMessage(), ex.getErrorCode()));
    }
}

50. 代码规范工具

public class CodeStandardUtils {
    // 常量命名
    public static final String CONSTANT_NAMING = "UPPER_CASE";
    
    // 变量命名
    private String variableNaming = "camelCase";
    
    // 方法命名
    public void methodNaming() {
        // 使用动词开头
    }
    
    // 类命名
    public class ClassNaming {
        // 使用大驼峰命名法
    }
    
    // 包命名
    package com.example.project;
    
    // 注释规范
    /**
     * 方法说明
     * @param param 参数说明
     * @return 返回值说明
     * @throws Exception 异常说明
     */
    public String commentStandard(String param) throws Exception {
        return param;
    }
}

写在最后 🧠💭

说了这么多,其实我想表达的很简单:

我们都在技术这条路上摸索,但没人真的一开始就什么都会。

希望这些内容能在你卡住的时候,给你一点思路、一点勇气。如果有共鸣、或者你也有更好的思考,欢迎随时交流。

非鱼牛马社,我们下次继续唠。