Đến nội dung chính
Sổ ôn Backend

Tìm kiếm

SpringMid23 phút đọc

Spring AOP và BeanPostProcessor: proxy, pointcut và thứ tự advice

Ôn 15 thẻ
Trong bài này

Cả bài trong một trang: ý chính, sơ đồ, điểm phỏng vấn.

Spring AOP và BeanPostProcessor: proxy, pointcut và thứ tự advice

1AOP và từ vựng

Aspect gom việc lặp ở nhiều method (log, transaction, phân quyền) vào một chỗ. Pointcut chọn chạy ở đâu, advice là chạy gì.

@Aspect @Component
class TimingAspect {
  @Around("@annotation(com.shop.Timed)")
  Object time(ProceedingJoinPoint pjp)
      throws Throwable {
    long t0 = System.nanoTime();
    try { return pjp.proceed(); }
    finally { log(System.nanoTime() - t0); }
  }
}

2Proxy được tạo thế nào

Một BeanPostProcessor (auto-proxy creator) bọc bean bằng proxy ở bước postProcessAfterInitialization. Chỉ lời gọi đi qua proxy mới chạy advice.

flowchart TD
  A["BFPP sửa BeanDefinition"] --> B["Tạo instance + inject"]
  B --> C["BPP before, @PostConstruct"]
  C --> D["BPP after: tạo proxy"]
  D --> E["Caller gọi proxy"]
  E --> F["Chuỗi advice"]
  F --> G["Object thật"]

3Thứ tự advice

Trong một aspect, @After giống finally: luôn chạy. Giữa các aspect, @Order nhỏ hơn bọc ngoài cùng: vào trước, ra sau.

  • @Around trước → @Before → method
  • → @AfterReturning hoặc @AfterThrowing
  • → @After → @Around sau
  • Chọn advice yếu nhất đủ dùng, @Around dễ quên proceed()

4Proxy không chặn được gì

Boot mặc định dùng CGLIB (lớp con lúc chạy); JDK proxy chỉ có kiểu interface. Gọi this.method() không qua proxy: đó là self-invocation.

Không chặn Vì sao
this.audit() Không đi qua proxy
private, final, static CGLIB không override được
Constructor, field Spring AOP chỉ có join point method

5BFPP, BPP và AspectJ

BFPP sửa định nghĩa bean trước khi tạo; BPP sửa hoặc thay instance sau khi tạo. AspectJ gắn vào bytecode nên chặn cả lời gọi nội bộ.

Làm việc với Ví dụ
BFPP BeanDefinition thay ${...}
BPP Instance @Autowired, tạo proxy AOP
AspectJ Bytecode method private, constructor

💡 Ghi nhớ

  • Không có BPP thì không có AOP.

  • @Order nhỏ là búp bê ngoài cùng.

  • Retry phải bọc ngoài @Transactional: mỗi lần thử một transaction.

  • @Around luôn return pjp.proceed().

⭐ Điểm phỏng vấn

Tự trả lời trước, rồi bấm từng câu để xem đáp án.

  • Aspect "không chạy", kiểm gì?

    Self-invocation, method private/final, bean không phải proxy.

  • JDK proxy và CGLIB?

    Interface so với lớp con; Boot mặc định CGLIB.

  • BPP và BFPP?

    BPP sửa instance, BFPP sửa định nghĩa bean.

⚠️ Lỗi thường gặp

  • Inject service vào BPP: service tạo quá sớm, mất mọi aspect, chỉ có WARN.

  • Retry nằm trong transaction: lần thử lại chạy trên transaction đã hỏng.

  • Pointcut execution(* *(..)) khớp cả bean framework, khởi động chậm.

Bài này giải thích @Transactional, @Async, @Cacheable hay một aspect log tự viết thực sự chạy thế nào: ai tạo proxy, lúc nào, và advice nào chạy trước. Đọc xong, bạn viết được aspect đúng, đoán được thứ tự khi nhiều aspect cùng khớp, và chẩn đoán được vì sao một aspect “không chạy”. Nên đọc trước phần proxy và vòng đời bean trong IoC và Dependency Injection.

Sơ đồ tóm tắt:

flowchart LR
  BD[BeanDefinition] --> BF[BFPP sửa định nghĩa]
  BF --> NEW[Tạo instance + inject]
  NEW --> B1[BPP before + @PostConstruct]
  B1 --> INIT[afterPropertiesSet, init-method]
  INIT --> B2[BPP after: auto-proxy creator]
  B2 --> PX[Proxy vào context]
  C[Caller] --> PX
  PX --> ADV[Chuỗi advice theo @Order]
  ADV --> T[Object thật]
  T -. "this.method()" .-> T

1. Cross-cutting concern và từ vựng của AOP

Ý chính: cross-cutting concern là việc không thuộc nghiệp vụ nhưng xuất hiện ở rất nhiều method. AOP gom nó vào một aspect, rồi chỉ ra “chạy ở đâu” (pointcut) và “chạy gì” (advice).

Không có AOP, mỗi method service tự mở transaction, tự log, tự đo giờ: code lặp, sửa một quy tắc log là sửa trăm chỗ. AOP giữ code nghiệp vụ sạch và đặt quy tắc ở một nơi.

Thuật ngữ Nghĩa (trong Spring AOP)
Aspect Class gom pointcut + advice, đánh @Aspect và là một bean
Join point Điểm có thể chen vào. Spring AOP chỉ có một loại: thực thi method trên bean
Pointcut Biểu thức chọn join point, ví dụ execution(* com.shop.order..*(..))
Advice Code chạy tại join point: @Before, @After, @AfterReturning, @AfterThrowing, @Around
Target Object thật bị bọc
Proxy Object Spring đưa vào context thay cho target
Weaving Việc gắn aspect vào code. Spring AOP gắn lúc chạy bằng proxy; AspectJ gắn vào bytecode
@Aspect
@Component
public class TimingAspect {
    @Around("@annotation(com.shop.Timed)")          // pointcut: method có @Timed
    public Object time(ProceedingJoinPoint pjp) throws Throwable {
        long t0 = System.nanoTime();
        try {
            return pjp.proceed();                    // gọi advice kế tiếp hoặc method thật
        } finally {
            log.info("{} took {} µs", pjp.getSignature().toShortString(),
                     (System.nanoTime() - t0) / 1_000);
        }
    }
}

Spring Boot tự bật @EnableAspectJAutoProxy khi có starter AOP (spring-boot-starter-aop; Boot 4 đổi tên thành spring-boot-starter-aspectj), nên không cần tự khai báo.

2. Pointcut: chọn method nào

Ý chính: pointcut là bộ lọc. Hay dùng nhất là execution(...) theo package/chữ ký, @annotation(...) theo annotation trên method, và within/bean theo class hay tên bean; ghép bằng &&, ||, !.

Biểu thức Khớp với
execution(public * com.shop.order.OrderService.*(..)) Mọi method public của OrderService
execution(* com.shop..*Service.*(..)) Mọi method của class tên kết thúc Service trong com.shop và package con (..)
@annotation(com.shop.Timed) Method có @Timed
@within(org.springframework.stereotype.Service) Mọi method của class có @Service
within(com.shop.payment..*) Mọi method của class trong package payment
bean(*Controller) Bean có tên kết thúc Controller (chỉ Spring AOP có)
args(id, ..) && execution(* find*(..)) Method find* và gắn tham số đầu vào biến id
  • Đặt tên cho pointcut dùng lại: @Pointcut("within(com.shop..service..*)") void serviceLayer() {} rồi @Before("serviceLayer() && @annotation(audited)").
  • Gắn annotation vào tham số advice để đọc giá trị: @Around("@annotation(timed)") Object x(ProceedingJoinPoint p, Timed timed).
  • Pointcut hẹp và rõ: execution(* *(..)) khớp mọi bean, kể cả bean của framework, làm khởi động chậm và dễ sinh lỗi lạ.
Cú pháp đầy đủ của execution và chi phí khớp pointcut

Dạng đầy đủ: execution(modifiers? return-type declaring-type? method-name(params) throws?).

  • * một phần tên bất kỳ; .. trong package là “package này và con”; (..) là mọi tham số, (*) đúng một tham số, (String, ..) tham số đầu là String.
  • Kiểu trả về và tên method là bắt buộc; còn lại tuỳ chọn.

Chi phí: Spring khớp pointcut lúc tạo bean (bean nào cần proxy, method nào có advice) và cache kết quả theo method, nên lúc chạy gần như không tốn thêm. Cái tốn là số bean bị proxy và số advice trên chuỗi. Pointcut @annotation/within lọc nhanh hơn execution dùng wildcard khắp nơi vì loại được class sớm.

3. Năm loại advice và thứ tự chạy

Ý chính: trong cùng một aspect, thứ tự là @Around (phần trước) → @Before → method → @AfterReturning hoặc @AfterThrowing → @After → @Around (phần sau). @After giống finally: luôn chạy.

Advice Chạy khi Đổi được kết quả? Dùng cho
@Before Trước method Không (chỉ chặn bằng cách ném exception) Kiểm quyền, validate tham số
@AfterReturning Method trả về bình thường Không (đọc được returning) Audit kết quả, metric thành công
@AfterThrowing Method ném exception Không nuốt được; đổi được bằng cách ném exception khác Đổi exception kỹ thuật sang nghiệp vụ, log lỗi
@After Luôn chạy (như finally) Không Dọn dẹp, trả tài nguyên
@Around Bọc toàn bộ Có: gọi hay không, đổi tham số, đổi kết quả Transaction, retry, cache, đo thời gian

Chạy thật trên Spring 7.0.10 (một aspect có đủ @Around, @Before, @AfterReturning, @After):

  [2] timing around: before
  [2] timing before
  [2] timing afterReturning: placed, then audited
  [2] timing after (finally)
  [2] timing around: after

Chọn advice yếu nhất đủ dùng: cần đọc kết quả thì @AfterReturning, đừng dùng @Around chỉ để log. @Around mạnh nhưng dễ quên proceed() hay nuốt exception.

4. Nhiều aspect cùng khớp: @Order và aspect của framework

Ý chính: aspect có @Order (hoặc Ordered) nhỏ hơn có độ ưu tiên cao hơn: nó vào trước và ra sau, tức là bọc ngoài cùng. Không đặt thứ tự thì thứ tự giữa hai aspect là không xác định.

Hai aspect SecurityAspect (@Order(1)) và TimingAspect (@Order(2)) trên cùng method:

  [1] security around: before placeOrder
  [2] timing around: before
  ...method...
  [2] timing around: after
  [1] security around: after

Giống búp bê lồng nhau: số nhỏ là con búp bê ngoài cùng. Áp vào aspect của framework:

  • @Transactional, @Cacheable cũng là advisor, mặc định thứ tự Ordered.LOWEST_PRECEDENCE, tức là trong cùng nếu aspect của bạn có @Order bất kỳ. Đổi được bằng @EnableTransactionManagement(order = ...).
  • Aspect retry phải bọc ngoài transaction: mỗi lần thử là một transaction mới. Nếu retry nằm trong, lần thử thứ hai chạy trong transaction đã bị đánh dấu rollback.
  • Aspect kiểm quyền nên ở ngoài cùng để không mở transaction hay chạm cache cho request bị từ chối.

5. Proxy: JDK hay CGLIB, và những gì proxy không chặn được

Ý chính: bean có interface có thể được bọc bằng JDK dynamic proxy (implement cùng interface), bean không có interface bằng CGLIB (lớp con tạo lúc chạy). Spring Boot mặc định dùng CGLIB cho mọi bean (spring.aop.proxy-target-class=true).

Chạy với @EnableAspectJAutoProxy(proxyTargetClass = false) (mặc định của Spring Framework thuần):

PaymentService -> $Proxy23 jdk=true
OrderService   -> OrderService$$SpringCGLIB$$0 cglib=true
  • JDK proxy chỉ là kiểu interface: inject theo class cụ thể (PaymentServiceImpl) sẽ lỗi BeanNotOfRequiredTypeException. Đây là lý do Boot chọn CGLIB làm mặc định.
  • CGLIB không override được method final/private/static, không kế thừa được class final. Kotlin class mặc định final nên cần plugin kotlin-spring (all-open).
  • So sánh bean.getClass() == OrderService.class luôn sai với bean có proxy; dùng AopUtils.getTargetClass(bean).

Bảng so sánh chi tiết JDK/CGLIB đã có ở IoC và Dependency Injection (mục 8).

Self-invocation: placeOrder() gọi audit() qua this, nên chỉ có một vòng advice cho placeOrder dù audit cũng có @Timed. Gọi order.audit() từ bên ngoài mới chạy advice cho audit. Đây là bản chất của proxy, không phải lỗi.

6. Spring AOP và AspectJ

Ý chính: Spring AOP dùng cú pháp pointcut của AspectJ nhưng gắn aspect lúc chạy bằng proxy, chỉ cho bean và chỉ cho method. AspectJ gắn thẳng vào bytecode nên chặn được gần như mọi thứ, đổi lại phải có bước weaving.

Spring AOP AspectJ
Gắn aspect Lúc chạy, bằng proxy Lúc compile, sau compile, hoặc lúc nạp class (agent)
Áp cho Bean Spring Mọi class, kể cả new tự tạo
Join point Thực thi method public/protected gọi qua proxy Method (cả private), constructor, đọc/ghi field, static init
Self-invocation Không chặn Chặn
Hiệu năng Thêm một tầng gọi qua proxy và chuỗi interceptor Gần như gọi thẳng
Độ phức tạp Không cần gì thêm Cần ajc hoặc -javaagent, IDE/debug khó hơn

Với ứng dụng nghiệp vụ, Spring AOP đủ cho hầu hết nhu cầu. Lưu ý: @Aspect là annotation của AspectJ, và Spring cần thư viện aspectjweaver chỉ để đọc cú pháp pointcut, không phải để weaving.

7. BeanPostProcessor và BeanFactoryPostProcessor

Ý chính: BeanFactoryPostProcessor (BFPP) chạy một lần, trước khi tạo bean nào, và sửa BeanDefinition (bản mô tả bean). BeanPostProcessor (BPP) chạy cho từng bean sau khi tạo, và có thể trả về object khác (proxy).

Chạy thật thứ tự vòng đời trên Spring 7.0.10 (một BFPP, một BPP tự viết, bean có đủ callback):

0 BFPP: 15 definitions, no bean instance of ours yet
1 constructor
2 inject setter
3 BeanNameAware: lifecycleBean
4 BPP before (lifecycleBean)
5 @PostConstruct
6 afterPropertiesSet
7 init-method
8 BPP after (lifecycleBean)
...
D1 @PreDestroy
D2 DisposableBean.destroy
D3 destroy-method
BeanFactoryPostProcessor BeanPostProcessor
Lúc nào Sau khi nạp mọi định nghĩa, trước khi tạo bean Quanh bước khởi tạo của từng bean
Làm việc với BeanDefinition Instance
Ví dụ trong Spring ConfigurationClassPostProcessor (xử lý @Configuration, @ComponentScan, @Bean), PropertySourcesPlaceholderConfigurer (thay ${...}) AutowiredAnnotationBeanPostProcessor (@Autowired, @Value), CommonAnnotationBeanPostProcessor (@PostConstruct, @Resource), auto-proxy creator (AOP), ConfigurationPropertiesBindingPostProcessor
Khai báo @Bean Phải là method static Nên là method static
  • @Autowired field/setter được inject ở bước populate (postProcessProperties của AutowiredAnnotationBeanPostProcessor), trước mọi init callback.
  • @PostConstruct chạy bên trong postProcessBeforeInitialization của CommonAnnotationBeanPostProcessor. Post-processor nội bộ này được đăng ký lại ở cuối danh sách, nên BPP của bạn thấy bean trước khi @PostConstruct chạy (dòng 4 trước dòng 5).
  • Thứ tự init: @PostConstruct → afterPropertiesSet() → init-method. Thứ tự destroy cũng theo kiểu đó: @PreDestroy → destroy() → destroy-method. Prototype bean không có destroy callback.
  • Nhiều BPP: nhóm PriorityOrdered trước, rồi Ordered, rồi phần còn lại.
Code lab: BFPP, BPP và hai aspect trên Spring 7.0.10

Chạy bằng JDK 21 với các jar spring-context, spring-aop, spring-beans, spring-core, spring-expression 7.0.10, aspectjweaver 1.9.25.1, jakarta.annotation-api 3.0.0 trên classpath (không cần Spring Boot).

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Timed {}

interface PaymentService { String pay(long amount); }
@Component class PaymentServiceImpl implements PaymentService {
  @Timed public String pay(long amount) { return "paid " + amount; }
}
@Component class OrderService {
  @Timed public String placeOrder() { return "placed, then " + audit(); } // this.audit()
  @Timed public String audit() { return "audited"; }
}

@Aspect @Component @Order(1) class SecurityAspect {
  @Around("@annotation(lab.Timed)")
  public Object around(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("  [1] security around: before " + pjp.getSignature().getName());
    Object r = pjp.proceed();
    System.out.println("  [1] security around: after");
    return r;
  }
}
@Aspect @Component @Order(2) class TimingAspect {
  @Around("@annotation(lab.Timed)")
  public Object around(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("  [2] timing around: before");
    try { return pjp.proceed(); } finally { System.out.println("  [2] timing around: after"); }
  }
  @Before("@annotation(lab.Timed)") public void before() { System.out.println("  [2] timing before"); }
  @After("@annotation(lab.Timed)") public void after() { System.out.println("  [2] timing after (finally)"); }
  @AfterReturning(pointcut = "@annotation(lab.Timed)", returning = "r")
  public void ret(Object r) { System.out.println("  [2] timing afterReturning: " + r); }
}

class TracingBpp implements BeanPostProcessor {
  public Object postProcessBeforeInitialization(Object b, String n) {
    if (b instanceof LifecycleBean) System.out.println("4 BPP before (" + n + ")");
    return b;
  }
  public Object postProcessAfterInitialization(Object b, String n) {
    if (b instanceof LifecycleBean) System.out.println("8 BPP after (" + n + ")");
    return b;
  }
}
class CountingBfpp implements BeanFactoryPostProcessor {
  public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) {
    System.out.println("0 BFPP: " + bf.getBeanDefinitionCount() + " definitions, no bean instance of ours yet");
  }
}

@Configuration @ComponentScan("lab") @EnableAspectJAutoProxy(proxyTargetClass = false)
class AppConfig {
  @Bean static CountingBfpp countingBfpp() { return new CountingBfpp(); }
  @Bean static TracingBpp tracingBpp() { return new TracingBpp(); }
  @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
  LifecycleBean lifecycleBean() { return new LifecycleBean(); }
}

LifecycleBean in một dòng ở constructor, setter @Autowired, setBeanName, @PostConstruct, afterPropertiesSet, initMethod, @PreDestroy, destroy, destroyMethod. main tạo AnnotationConfigApplicationContext, in kiểu của hai bean, gọi order.placeOrder() rồi order.audit(), cuối cùng close(). Kết quả gọi placeOrder():

  [1] security around: before placeOrder
  [2] timing around: before
  [2] timing before
  [2] timing afterReturning: placed, then audited
  [2] timing after (finally)
  [2] timing around: after
  [1] security around: after
result: placed, then audited

Chỉ một vòng advice: audit() gọi qua this không đi qua proxy.

8. Khi nào tự viết BPP, khi nào viết aspect

Ý chính: viết aspect khi muốn chen logic quanh lời gọi method; viết BPP khi muốn xử lý bean lúc khởi tạo (đọc annotation riêng, đăng ký vào registry, bọc proxy theo kiểu riêng). Phần lớn ứng dụng nghiệp vụ không cần BPP.

Nhu cầu Chọn
Log, đo giờ, audit, retry quanh method Aspect @Around/@AfterReturning
Khởi tạo cho một bean @PostConstruct hoặc ApplicationRunner
Mọi bean có @KafkaHandler tự viết phải được đăng ký vào một registry BPP (postProcessAfterInitialization)
Thay giá trị trong định nghĩa bean trước khi tạo (placeholder, đổi class) BFPP
Đăng ký thêm bean theo quét riêng BeanDefinitionRegistryPostProcessor hoặc ImportBeanDefinitionRegistrar

Spring tự dùng nhiều design pattern quanh cơ chế này: Proxy (AOP), Template Method (JdbcTemplate, TransactionTemplate), Factory (BeanFactory, FactoryBean), Singleton (scope mặc định), Front Controller (DispatcherServlet), Adapter (HandlerAdapter), Observer (ApplicationEvent).

Bài tập

Bài 1: Đoán output

Có SecurityAspect @Order(1) chỉ có @Around, và TimingAspect @Order(2) có @Around, @Before, @AfterReturning, @After như phần lab. OrderService.placeOrder() có @Timed và gọi this.audit() (cũng @Timed). Viết ra thứ tự các dòng in khi gọi orderService.placeOrder() từ một bean khác. Nếu đổi @Order của hai aspect cho nhau thì sao?

Lời giải Bài 1

Thứ tự đúng (đã chạy trên Spring 7.0.10):

[1] security around: before placeOrder
[2] timing around: before
[2] timing before
[2] timing afterReturning: placed, then audited
[2] timing after (finally)
[2] timing around: after
[1] security around: after
  • Aspect @Order(1) bọc ngoài: vào trước, ra sau.
  • Trong TimingAspect: around (trước) → before → method → afterReturning → after → around (sau).
  • audit() không có dòng nào riêng vì gọi qua this.

Đổi @Order cho nhau: toàn bộ khối [2] (năm dòng) nằm ngoài, khối [1] (hai dòng) nằm trong, sát method. Thứ tự bên trong mỗi aspect không đổi.

Bài 2: Vì sao aspect không chạy

Một team có TenantBeanPostProcessor implements BeanPostProcessor, PriorityOrdered, constructor nhận AuditService để ghi log mỗi khi có bean tenant được tạo. AuditService.record() có @Audited và một aspect @Around("@annotation(Audited)"). Gọi record() thì aspect không chạy, không có exception. Giải thích và sửa.

Lời giải Bài 2

Thí nghiệm tái hiện (Spring 7.0.10):

class EagerBpp implements BeanPostProcessor, PriorityOrdered {
  public int getOrder() { return 0; }
  final AuditService audit;
  EagerBpp(AuditService audit) { this.audit = audit; }
}
@Configuration @ComponentScan("lab2") @EnableAspectJAutoProxy
class Cfg { @Bean static EagerBpp eagerBpp(AuditService a) { return new EagerBpp(a); } }
WARNING: Bean 'auditService' of type [lab2.AuditService] is not eligible for getting processed
by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting
eagerly injected/applied to a currently created BeanPostProcessor [eagerBpp]? ...
AuditService is proxy? false
    record x

Giải thích: Spring tạo các BPP PriorityOrdered đầu tiên. Để tạo EagerBpp nó phải tạo AuditService ngay lúc đó, khi bộ tạo proxy AOP (một BPP Ordered) chưa được đăng ký. AuditService vào context dưới dạng object thật và không bao giờ được bọc.

Khi bỏ PriorityOrdered (BPP thường), cùng code vẫn in WARN nhưng AuditService lại có proxy, vì bộ tạo proxy đã đăng ký trước nhóm BPP thường. Tức là lỗi phụ thuộc thứ tự, rất khó đoán; đừng dựa vào nó.

Sửa:

  1. Không inject bean nghiệp vụ vào BPP. Nếu cần, nhận ObjectProvider<AuditService> và gọi getObject() lúc xử lý bean.
  2. Khai báo BPP bằng @Bean static.
  3. Thêm vào checklist khởi động: grep log tìm not eligible for getting processed by all BeanPostProcessors.

Ghi nhớ

  • Giải thích được ai tạo proxy AOP, ở bước nào của vòng đời bean, và vì sao this.method() không qua aspect.
  • Viết ra được thứ tự năm loại advice trong một aspect và thứ tự giữa hai aspect có @Order.
  • Biết đặt aspect retry ở ngoài @Transactional và cách kiểm điều đó.
  • Phân biệt được BFPP và BPP, kể được ví dụ của mỗi loại trong Spring.
  • Nhận ra dòng WARN “not eligible for auto-proxying” và biết sửa.

Câu hỏi phỏng vấn

Junior

AOP là gì? Kể các khái niệm aspect, pointcut, advice, join point.

AOP tách việc cắt ngang nhiều nơi (log, transaction, phân quyền) ra khỏi code nghiệp vụ: aspect là module chứa nó, pointcut chọn chỗ áp, advice là code chạy ở đó, join point là điểm có thể chen vào (với Spring AOP: thực thi method).

Spring cài AOP bằng proxy bọc bean, nên chỉ lời gọi đi qua proxy mới có advice. @Transactional, @Cacheable, @Async, @PreAuthorize đều là ứng dụng của cơ chế này.

Kể vài design pattern Spring dùng bên trong.

Proxy (AOP, @Transactional), Template Method (JdbcTemplate, RestTemplate, TransactionTemplate), Factory (BeanFactory, FactoryBean), Singleton (scope mặc định), Front Controller (DispatcherServlet), Adapter (HandlerAdapter), Observer (ApplicationEvent/@EventListener).

Ý quan trọng hơn danh sách: DI cùng các pattern này cho phép framework chen hành vi (transaction, bảo mật) mà code nghiệp vụ không phụ thuộc vào framework.

Mid

Các loại advice chạy theo thứ tự nào? Khi nào dùng @Around?

Trong một aspect: @Around (trước) → @Before → method → @AfterReturning hoặc @AfterThrowing → @After → @Around (sau). Dùng @Around khi cần quyết định có gọi method không, đổi tham số hoặc kết quả, hay đo bao trọn.

@AfterThrowing không nuốt được exception; @After chạy như finally. Với @Around, luôn return pjp.proceed(); quên return là người gọi nhận null, method trả kiểu nguyên thuỷ thì nổ AopInvocationException.

Hai aspect cùng khớp một method, cái nào chạy trước?

Aspect có @Order nhỏ hơn bọc ngoài: chạy phần “trước” sớm nhất và phần “sau” muộn nhất. Không đặt thứ tự thì thứ tự là không xác định.

Advisor của @Transactional mặc định có thứ tự thấp nhất (LOWEST_PRECEDENCE). Aspect kiểm quyền nên ở ngoài cùng; aspect retry phải ở ngoài transaction để mỗi lần thử là transaction mới.

Spring AOP khác AspectJ thế nào?

Spring AOP gắn aspect lúc chạy bằng proxy, chỉ cho bean và chỉ cho lời gọi method qua proxy. AspectJ gắn vào bytecode (compile time hoặc load time), chặn được cả constructor, field, method private và lời gọi nội bộ.

Spring dùng cú pháp pointcut và annotation của AspectJ (@Aspect, @Around) nhưng không dùng weaver của nó. Chuyển sang AspectJ khi thật sự cần chặn self-invocation hoặc object không phải bean, chấp nhận thêm agent/plugin build.

JDK dynamic proxy và CGLIB khác nhau thế nào? Spring Boot mặc định dùng gì?

JDK proxy implement cùng interface với bean, nên chỉ inject được theo interface. CGLIB tạo lớp con lúc chạy, không cần interface nhưng không override được method final/private. Spring Boot mặc định CGLIB (spring.aop.proxy-target-class=true).

Spring Framework thuần (không Boot) dùng JDK proxy nếu bean có interface. Hệ quả của CGLIB: getClass() trả OrderService$$SpringCGLIB$$0, và constructor của lớp gốc không chạy hai lần nhờ Objenesis.

BeanPostProcessor và BeanFactoryPostProcessor khác nhau thế nào? Cho ví dụ.

BFPP chạy trước khi tạo bean, sửa BeanDefinition (ví dụ PropertySourcesPlaceholderConfigurer thay ${...}, ConfigurationClassPostProcessor xử lý @Configuration). BPP chạy cho từng instance sau khi tạo, có thể thay bằng proxy (ví dụ auto-proxy creator của AOP, AutowiredAnnotationBeanPostProcessor).

@ConfigurationProperties được bind bởi một BPP (ConfigurationPropertiesBindingPostProcessor), không phải BFPP như một số tài liệu ghi. Method @Bean trả BFPP phải là static, nếu không class @Configuration bị tạo quá sớm.

@PostConstruct, afterPropertiesSet() và init-method chạy theo thứ tự nào so với BeanPostProcessor?

Constructor → inject → Aware → BPP before (trong đó có @PostConstruct) → afterPropertiesSet() → init-method → BPP after (tạo proxy).

Trên Spring 7.0.10, BPP tự viết thấy bean trước @PostConstruct, vì CommonAnnotationBeanPostProcessor (chạy @PostConstruct) nằm cuối danh sách post-processor. Vì proxy tạo ở bước cuối, @Transactional gọi từ @PostConstruct của chính bean không có transaction.

Senior

Một aspect hoặc @Transactional “không chạy”. Bạn kiểm tra những gì?

Kiểm lần lượt: lời gọi có đi qua proxy không, method có chặn được không, pointcut có khớp không, bean có được bọc không, và thứ tự với aspect khác.

  • Self-invocation (this.x()), hoặc object tự new chứ không phải bean.
  • Method private/final/static, class final.
  • Pointcut sai package/annotation (annotation thiếu @Retention(RUNTIME)).
  • AopUtils.isAopProxy(bean) trả false: tìm WARN “not eligible for auto-proxying” (bean bị inject vào BPP).
  • Starter AOP thiếu hoặc aspect không phải bean (@Aspect không kèm @Component).
  • Có chạy nhưng sai thứ tự: in thứ tự advisor, đặt @Order.
Bạn cần retry khi gặp deadlock cho một method @Transactional. Đặt retry ở đâu?

Ở ngoài transaction: aspect retry có độ ưu tiên cao hơn advisor transaction (@Order nhỏ), hoặc gọi method transactional từ một bean khác có vòng retry.

Retry nằm trong transaction là vô ích: sau exception đầu tiên transaction thường đã hỏng (DB rollback nạn nhân deadlock, repository đánh dấu rollback-only), lần thử sau chạy trên transaction đó và commit ném UnexpectedRollbackException. Kèm backoff ngẫu nhiên, giới hạn số lần, chỉ retry lỗi tạm thời (deadlock, lock timeout), và method phải idempotent hoặc toàn bộ nằm trong một transaction.

Từ vựng tiếng Anh

Term Phát âm Nghĩa Ví dụ câu tiếng Anh dùng trong phỏng vấn
cross-cutting concern /krɔːs ˈkʌt.ɪŋ kənˈsɝːn/ việc cắt ngang nhiều module “Logging and transactions are cross-cutting concerns, so they live in aspects.”
aspect /ˈæs.pekt/ module AOP “The timing aspect wraps every method annotated with @Timed.”
pointcut /ˈpɔɪnt.kʌt/ biểu thức chọn điểm áp “The pointcut matches public methods in the service package.”
advice /ədˈvaɪs/ code chạy tại điểm áp “Around advice decides whether the method runs at all.”
join point /dʒɔɪn pɔɪnt/ điểm có thể chen vào “In Spring AOP the only join point is method execution.”
weaving /ˈwiː.vɪŋ/ gắn aspect vào code “AspectJ weaves at load time, Spring AOP uses runtime proxies.”
precedence /ˈpres.ə.dəns/ độ ưu tiên “The aspect with higher precedence runs first on the way in.”
self-invocation /self ˌɪn.vəˈkeɪ.ʃən/ tự gọi method trong cùng object “Self-invocation bypasses the proxy, so the advice never runs.”
post-processor /poʊst ˈprɑː.ses.ɚ/ bộ xử lý sau “The auto-proxy creator is a bean post-processor.”
eagerly /ˈiː.ɡɚ.li/ sớm, ngay lập tức “That service was created eagerly for a post-processor and lost its proxy.”

Ghi chép tự tổng hợp từ tài liệu chính thức và kinh nghiệm thực tế.