惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
云风的 BLOG
云风的 BLOG
小众软件
小众软件
雷峰网
雷峰网
博客园 - 【当耐特】
V
V2EX
WordPress大学
WordPress大学
IT之家
IT之家
Last Week in AI
Last Week in AI
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
The Cloudflare Blog
Jina AI
Jina AI
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
AOP Java Làm Gì Mà Giúp Code Sạch Hơn? (Giải Thích Từ A-Z)
ITPrep · 2026-05-07 · via DEV Community

ITPrep

Bài viết gốc tại: https://itprep.com.vn/aop-java-lap-trinh-huong-khia-canh/.

Trong lập trình Java, các chức năng như:

  • Logging
  • Security
  • Transaction
  • Caching

thường xuất hiện ở rất nhiều nơi trong codebase.

Những phần này được gọi là Cross-Cutting Concerns — và nếu xử lý không khéo, source code sẽ nhanh chóng trở nên rối, lặp logic và khó maintain.

Đó là lúc AOP (Aspect-Oriented Programming) phát huy sức mạnh.


AOP Là Gì?

AOP giúp tách các logic phụ trợ ra khỏi business logic chính.

Ví dụ thay vì viết logging trong từng method:

public void createUser() {

    System.out.println("Start");

    // business logic

    System.out.println("End");
}

Enter fullscreen mode Exit fullscreen mode

Ta có thể dùng AOP để tự động inject logging trước/sau method mà không sửa code gốc.

Kết quả:

  • Code sạch hơn
  • Dễ maintain hơn
  • Giảm lặp code
  • Reuse logic tốt hơn

Các Thành Phần Chính Trong AOP

Thành phần Ý nghĩa
Aspect Module chứa logic AOP
Join Point Điểm có thể can thiệp
Advice Hành động chạy tại Join Point
Pointcut Điều kiện chọn Join Point
Proxy Object trung gian của Spring

Spring AOP Hoạt Động Như Thế Nào?

Spring AOP hoạt động bằng Proxy:

Client -> Proxy -> Real Object

Enter fullscreen mode Exit fullscreen mode

Khi method được gọi:

  1. Proxy intercept request
  2. Chạy Advice
  3. Gọi method thật
  4. Chạy logic sau method

Spring thường dùng:

  • JDK Dynamic Proxy
  • CGLIB Proxy

Cấu Hình Spring AOP

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
}

Enter fullscreen mode Exit fullscreen mode


Ví Dụ Logging Với Spring AOP

UserService.java

package com.example.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public String getUserById(Long id) {

        System.out.println("Đang lấy user với ID: " + id);

        if (id <= 0) {
            throw new IllegalArgumentException("ID không hợp lệ");
        }

        return "User " + id;
    }

    public void createUser(String name) {
        System.out.println("Đang tạo user: " + name);
    }
}

Enter fullscreen mode Exit fullscreen mode

LoggingAspect.java

package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;

import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {

        System.out.println(
            "Calling: " +
            joinPoint.getSignature().toShortString()
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Toàn bộ method trong package service sẽ tự động được logging mà không cần sửa business logic.


Khi Nào Nên Dùng AOP?

AOP cực kỳ phù hợp cho:

  • Logging
  • Security
  • Transaction Management
  • Caching
  • Monitoring
  • Retry Logic

Khi NÀO KHÔNG Nên Dùng?

Không nên dùng nếu:

  • Logic chỉ xuất hiện ở vài class
  • Có thể giải quyết dễ bằng OOP
  • Aspect làm code khó debug

Một Điều Quan Trọng Về Spring AOP

Spring AOP dùng Proxy.

Nghĩa là:

this.someMethod()

Enter fullscreen mode Exit fullscreen mode

sẽ KHÔNG bị intercept.

Đây là lỗi phổ biến gọi là:

Self-invocation problem


AOP vs OOP

OOP AOP
Tập trung object Tập trung cross-cutting concerns
Logic theo chiều dọc Logic theo chiều ngang
Business logic Logging/Security/Transaction

AOP không thay thế OOP.

Nó là phần bổ sung cho OOP.


Kết Luận

AOP giúp:

  • Code sạch hơn
  • Giảm lặp logic
  • Tăng maintainability
  • Tách biệt cross-cutting concerns hiệu quả

Tuy nhiên:

Đừng lạm dụng AOP chỉ vì thấy nó "xịn".

Hãy dùng đúng nơi như logging, security, transaction hoặc monitoring.


Xem thêm các bài viết Java/Spring/Backend tại ITPrep.com.vn