Tổng Quan Về Apache Commons Trong Java

Apache Commons là một bộ sưu tập các thư viện công cụ mã nguồn mở quan trọng và phổ biến nhất trong hệ sinh thái Java. Nó bù đắp những thiếu sót của thư viện chuẩn JDK trong nhiều tình huống chung, cung cấp các công cụ chất lượng cao đã được kiểm chứng trong sản xuất.

Cho đến năm 2026, mặc dù các tính năng mới của Java 8-21 (như Stream, Optional, Var, Records) đã hấp thụ một số chức năng, nhưng Commons vẫn không thể thay thế về **tính tương thích, chiều sâu chức năng và các lĩnh vực chuyên biệt** (như thống kê toán học, mã hóa/giải mã, hỗ trợ các hệ thống cũ).

Dưới đây là **bức tranh toàn cảnh chức năng**, **mô tả nguyên lý ngắn gọn** và **ví dụ mã chi tiết** của các mô-đun chính.

Bức tranh toàn cảnh các mô-đun chính của Apache Commons

Mô-đunVị trí chínhỨng dụng điển hìnhTrạng thái
Commons LangCải tiến cấp ngôn ngữ (String, Object, Array)Xử lý chuỗi, sao chép đối tượng, thao tác mảngRất thường xuyên
Commons IOCải tiến thao tác luồng IOSao chép tệp, chuyển đổi luồng, giám sát sự thay đổi của tệpRất thường xuyên
Commons CollectionsCải tiến khung cấu trúc dữ liệuThao tác cấu trúc dữ liệu nâng cao, bản đồ hai chiều, bộ lọc BloomThường xuyên
Commons BeanUtilsThao tác thuộc tính JavaBeanGắn kết tham số web, sao chép đối tượng, thuộc tính độngThường xuyên
Commons CodecCông cụ mã hóa/giải mãBase64, MD5, SHA, mã hóa URLThường dùng
Commons TextXử lý văn bản (mở rộng từ Lang)Thay thế chuỗi, thoát chuỗi, tạo chuỗi ngẫu nhiênThường dùng
Commons MathToán học và thống kêPhân tích thống kê, đại số tuyến tính, thuật toán tối ưu hóaLĩnh vực chuyên môn
Commons ConfigurationQuản lý cấu hìnhĐọc các định dạng cấu hình khác nhau (XML, Properties, JSON)Lĩnh vực chuyên môn
Commons CLIGiải mã dòng lệnhGiải mã tham số khởi động (`-h`, `--port 8080`)Lĩnh vực chuyên môn
Commons PoolHóa các đối tượng thành poolBộ đệm kết nối cơ sở dữ liệu, tái sử dụng đối tượng trong pool luồngHỗ trợ cấp thấp

Commons Lang (`org.apache.commons:commons-lang3`)

Vị trí: Phiên bản nâng cao của gói `java.lang`. Giải quyết các điểm đau hàng ngày của `String`, `Object`, `Array`, `System`, v.v.

A. Xử lý chuỗi (`StringUtils`)


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.ArrayUtils;

public class VnLangDemo {
    public static void main(String[] args) {
        // 1. Kiểm tra giá trị rỗng (thay thế cho "".equals(s))
        System.out.println(StringUtils.isEmpty(null));      // true
        System.out.println(StringUtils.isBlank("   "));     // true (bao gồm khoảng trắng)
        System.out.println(StringUtils.isNotBlank("Xin chào"));   // true

        // 2. Thiết lập giá trị mặc định
        String ten = null;
        System.out.println(StringUtils.defaultString(ten, "Không rõ")); // "Không rõ"

        // 3. Thao tác chuỗi
        System.out.println(StringUtils.reverse("Chào bạn"));         // "ban ôaC"
        System.out.println(StringUtils.capitalize("xin chào mọi người"));// "Xin chào mọi người"
        System.out.println(StringUtils.join(new String[]{"A", "B"}, "-")); // "A-B"
        
        // 4. Thu gọn
        System.out.println(StringUtils.abbreviate("Apache Commons Việt Nam", 10)); // "Apache C..."
    }
}

B. Thao tác đối tượng (`ObjectUtils`, `ReflectionUtils`)


import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

class Nguoi {
    String ten; int tuoi;
    // constructor...
    @Override
    public String toString() {
        // Một dòng mã để tạo ra toString đẹp mắt, hỗ trợ phát hiện vòng lặp tham chiếu
        return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
    }
}

// Sử dụng
Nguoi n = new Nguoi("Jack", 25);
System.out.println(n); 
// Output: {"ten":"Jack","tuoi":25}

// So sánh an toàn (xử lý null)
System.out.println(ObjectUtils.equals(null, null)); // true
System.out.println(ObjectUtils.max(10, 20, 5));     // 20


C. Thao tác mảng (`ArrayUtils`)


int[] soHieu = {1, 2, 3};
soHieu = ArrayUtils.add(soHieu, 4);       // [1, 2, 3, 4]
soHieu = ArrayUtils.remove(soHieu, 0);    // [2, 3, 4]
ArrayUtils.reverse(soHieu);             // [4, 3, 2]
System.out.println(ArrayUtils.contains(soHieu, 3)); // true


Commons IO (`commons-io:commons-io`)

Vị trí: Đơn giản hóa các thao tác phức tạp của `java.io` và `java.nio`.

A. Đọc/ghi tệp (`FileUtils`)


import org.apache.commons.io.FileUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class IODemoVN {
    public static void main(String[] args) throws Exception {
        File file = new File("du_lieu.txt");

        // 1. Ghi vào tệp một cách dễ dàng (tự động tạo thư mục cha nếu cần)
        FileUtils.write(file, "Chào mừng tới Commons IO", StandardCharsets.UTF_8);

        // 2. Đọc tệp một cách dễ dàng
        String noiDung = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        
        // 3. Đọc nội dung dưới dạng danh sách dòng
        List<String> dong = FileUtils.readLines(file, StandardCharsets.UTF_8);

        // 4. Sao chép tệp/hướng dẫn
        FileUtils.copyFile(file, new File("backup.txt"));
        FileUtils.copyDirectory(new File("nguon"), new File("dich"));

        // 5. Xóa hướng dẫn (theo cấp độ đệ quy)
        // FileUtils.deleteDirectory(new File("tam"));
        
        // 6. Lấy kích thước tệp ở định dạng dễ đọc
        long kichThuoc = file.length();
        System.out.println(FileUtils.byteCountToDisplaySize(kichThuoc)); // "15 bytes"
    }
}


B. Thao tác luồng (`IOUtils`)


import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URL;

// Sao chép luồng (tự động đóng tài nguyên, không cần try-with-resources)
try (InputStream in = new FileInputStream("nguon.txt");
     OutputStream out = new FileOutputStream("dich.txt")) {
    IOUtils.copy(in, out); 
}

// Đọc nội dung từ URL
String html = IOUtils.toString(new URL("https://apache.org"), StandardCharsets.UTF_8);

// Chuyển đổi chuỗi lớn thành luồng đầu vào
InputStream stream = IOUtils.toInputStream("Dữ liệu lớn...", StandardCharsets.UTF_8);


C. Giám sát tệp (`FileMonitor`)


import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import java.io.File;

// Theo dõi sự thay đổi của thư mục
File thuMuc = new File("/var/log/appcuaanh");
FileAlterationObserver observer = new FileAlterationObserver(thuMuc);
observer.addListener(new FileAlterationListenerAdaptor() {
    @Override
    public void onFileCreate(File file) {
        System.out.println("Tệp mới được tạo: " + file.getName());
    }
    @Override
    public void onFileChange(File file) {
        System.out.println("Tệp đã được sửa đổi: " + file.getName());
    }
});
// Cần kết hợp với Timer hoặc luồng để gọi observer.checkAndNotify() theo định kỳ


Commons Collections (`org.apache.commons:commons-collections4`)

Vị trí: Cấu trúc dữ liệu nâng cao vượt qua `java.util`.

A. Bản đồ hai chiều (`BidiMap`)


import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;

BidiMap map = new TreeBidiMap<>();
map.put("Một", 1);
map.put("Hai", 2);

System.out.println(map.get("Một"));   // 1
System.out.println(map.getKey(2));    // "Hai" (không thể làm được với Map gốc)
map.removeValue(1);                   // Xóa dựa trên giá trị


B. Bản đồ đa giá trị (`MultiValuedMap`)


import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;

MultiValuedMap multiMap = new ArrayListValuedHashMap<>();
multiMap.put("Trái cây", "Táo");
multiMap.put("Trái cây", "Chuối");
multiMap.put("Màu sắc", "Đỏ");

System.out.println(multiMap.get("Trái cây")); // [Táo, Chuối]
System.out.println(multiMap.keySet());     // [Trái cây, Màu sắc]


C. Bộ công cụ xử lý cấu trúc dữ liệu (`CollectionUtils`)


import org.apache.commons.collections4.CollectionUtils;
import java.util.*;

List<Integer> danhSach1 = Arrays.asList(1, 2, 3, 4);
List<Integer> danhSach2 = Arrays.asList(3, 4, 5, 6);

// Giao
Collection<Integer> giao = CollectionUtils.intersection(danhSach1, danhSach2); // [3, 4]
// Hợp
Collection<Integer> hop = CollectionUtils.union(danhSach1, danhSach2);               // [1, 2, 3, 4, 5, 6]
// Hiệu (danhSach1 có nhưng danhSach2 không có)
Collection<Integer> hieu = CollectionUtils.subtract(danhSach1, danhSach2);         // [1, 2]

// Kiểm tra trống
if (CollectionUtils.isNotEmpty(danhSach1)) { ... }


Commons Codec (`commons-codec:commons-codec`)

Vị trí: Thực hiện các thuật toán mã hóa/giải mã thông dụng.


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import java.nio.charset.StandardCharsets;

public class CodecDemoVN {
    public static void main(String[] args) throws Exception {
        String duLieu = "MatKhauBiMat 123";

        // 1. Tóm tắt băm (MD5, SHA-1, SHA-256)
        String md5 = DigestUtils.md5Hex(duLieu);
        String sha256 = DigestUtils.sha256Hex(duLieu);
        System.out.println("MD5: " + md5);

        // 2. Mã hóa/giải mã Base64
        byte[] maHoa = Base64.encodeBase64(duLieu.getBytes(StandardCharsets.UTF_8));
        String base64Str = new String(maHoa, StandardCharsets.UTF_8);
        byte[] giaiMa = Base64.decodeBase64(base64Str);
        System.out.println("Base64: " + base64Str);

        // 3. Mã hóa/giải mã URL (xử lý ký tự đặc biệt)
        URLCodec codec = new URLCodec();
        String urlDuLieu = "a b & c=d";
        String maHoaUrl = codec.encode(urlDuLieu); // "a+b+%26+c%3Dd"
        System.out.println("URL Encoded: " + maHoaUrl);
    }
}


Commons Text (`org.apache.commons:commons-text`)

Vị trí: Thư viện xử lý văn bản nâng cao tách ra từ Lang 3 (từ Lang 3.6+ bắt đầu độc lập).


import org.apache.commons.text.StringSubstitutor;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.commons.text.translate.EscapeHtml;
import java.util.HashMap;
import java.util.Map;

public class TextDemoVN {
    public static void main(String[] args) {
        // 1. Thay thế mẫu chuỗi (giống như phiên bản đơn giản của Velocity)
        Map giaTri = new HashMap<>();
        giaTri.put("ten", "Alice");
        giaTri.put("congViec", "Kỹ sư");

        String mau = "Xin chào ${ten}, bạn là một ${congViec}.";
        StringSubstitutor thayThe = new StringSubstitutor(giaTri);
        String ketQua = thayThe.replace(mau);
        System.out.println(ketQua); // "Xin chào Alice, bạn là một Kỹ sư."

        // 2. Thoát HTML (chống XSS)
        String html = "<script>alert('xss')</script>";
        String htmlAnToan = EscapeHtml.escapeHtml4(html);
        System.out.println(htmlAnToan); // "<script>alert('xss')</script>"

        // 3. Tạo chuỗi ngẫu nhiên
        // Lưu ý: RandomStringGenerator trong các phiên bản mới hơn bị đánh dấu, khuyến nghị sử dụng SecureRandom hoặc trình tạo cụ thể
        // Đoạn mã này chỉ minh họa cách sử dụng cũ, phiên bản mới nên xem tài liệu để di chuyển sang TextRandomGenerator
        /* 
        RandomStringGenerator generator = new RandomStringGenerator.Builder()
            .withinRange('a', 'z').build();
        System.out.println(generator.generate(10)); 
        */
    }
}


Các mô-đun chuyên nghiệp khác

A. Commons Math (`commons-math3` / `commons-numbers`)

Được sử dụng cho tính toán khoa học.


// Ví dụ thống kê
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;

DescriptiveStatistics stats = new DescriptiveStatistics();
stats.addValue(10); stats.addValue(20); stats.addValue(30);
System.out.println("Trung bình: " + stats.getMean());   // Giá trị trung bình
System.out.println("Độ lệch chuẩn: " + stats.getStandardDeviation()); // Độ lệch chuẩn


B. Commons CLI (`commons-cli:commons-cli`)

Giải mã các tham số dòng lệnh.


import org.apache.commons.cli.*;

Options options = new Options();
options.addOption("p", "port", true, "Cổng máy chủ");
options.addOption("h", "help", false, "In ra trợ giúp");

CommandLineParser parser = new DefaultParser();
try {
    CommandLine cmd = parser.parse(options, new String[]{"-p", "8080", "-h"});
    if (cmd.hasOption("help")) {
        // In ra trợ giúp
    }
    String port = cmd.getOptionValue("port"); // "8080"
} catch (ParseException e) {
    e.printStackTrace();
}


C. Commons Pool (`commons-pool2`)

Kỹ thuật hóa các đối tượng thành pool, là nền tảng cho các pool kết nối cơ sở dữ liệu (như DBCP).


// Tạo nhà máy đối tượng tùy chỉnh, thực thi giao diện PooledObjectFactory
// Tạo GenericObjectPool<MyObject> pool = new GenericObjectPool<>(factory);
// MyObject obj = pool.borrowObject();
// pool.returnObject(obj);


Thực hành tốt nhất và lưu ý

  • Luôn sử dụng **Commons Lang 3.x** (tên gói `org.apache.commons.lang3`), không sử dụng Lang 2.x lỗi thời.
  • Sử dụng **Collections 4.x**.
  • Sử dụng **IO 2.x**.

Apache Commons là "dao quân đội Thụy Sĩ" của lập trình viên Java.

  • Cần thiết cho phát triển hàng ngày: **Lang, IO, Collections**.
  • Cần thiết cho phát triển web/framework: **BeanUtils, Codec**.
  • Nhập các lĩnh vực cụ thể theo yêu cầu: **Math, CLI, Configuration, Pool**.

Thẻ: Java ApacheCommons Lang io Collections

Đăng vào ngày 29 tháng 5 lúc 04:57