AOP proxies and transaction boundaries
What you will learn
Aspect-oriented programming separates cross-cutting behavior, such as timing or transaction management, from business logic. A Spring AOP proxy intercepts eligible calls that pass through it. Calls made directly on the target, including self-invocation, do not cross that boundary in ordinary proxy mode.
- Trace external and self-invoked calls.
- Explain transaction manager and rollback boundaries.
- Refactor a self-invocation into a separate injected service.
Plain Java examples use javac --release 21 Main.java then java Main in a fresh folder. Framework examples require the separate pinned Maven lab; their outputs are predictions from source review, not execution evidence. Do not copy all files into one Main.java.
Observe an explicit wrapper boundary
public class Main { interface Service { void outer(); void inner(); } static final class Target implements Service { public void outer() { System.out.println("outer"); inner(); } public void inner() { System.out.println("inner"); } } static final class Wrapper implements Service { final Service target; Wrapper(Service target) { this.target = target; } public void outer() { System.out.println("before outer"); target.outer(); } public void inner() { System.out.println("before inner"); target.inner(); } } public static void main(String[] args) { Service service = new Wrapper(new Target()); service.outer(); service.inner(); }}Expected output:
before outerouterinnerbefore innerinnerThe inner call inside Target does not go through Wrapper. This models proxy boundaries without Spring.
Advice and interception
An aspect groups cross-cutting behavior. A pointcut selects eligible method executions; advice runs before, after or around a selected execution. Around advice may invoke the next step with proceed(), return a result or propagate an exception. Spring AOP works through JDK interface proxies or subclass proxies; a final class cannot be subclassed, and final/private methods cannot be overridden for subclass interception. Interface proxy calls must be available through the exposed interface. An ordinary call on this stays on the target. Prefer moving the advised operation to another injected bean rather than reaching back into proxy machinery.
Transactions are runtime behavior
@Transactional is metadata interpreted by configured transaction infrastructure, not an automatic database operation. Enable declarative management and provide a suitable PlatformTransactionManager (for example one bound to the same JDBC DataSource used by the repository). Place the boundary on a service method reached through the proxy. The usual imperative transaction is thread-bound; a new executor thread does not automatically join it. With default rollback rules unchecked exceptions and Errors trigger rollback; checked exceptions do not unless configured. Use rollbackFor for an intended checked failure and avoid swallowing errors that should cause rollback. Default REQUIRED joins an existing transaction or creates one. REQUIRES_NEW uses a separate physical transaction and may require another connection. Read-only is a hint, not authorization. Real commit, rollback and isolation need a real resource and integration tests.
A controlled Spring proxy demonstration
The companion ProxyDemo creates a ProxyFactory around a fixed target, adds a MethodInterceptor, and invokes an interface method. It is an AOP example, not a transaction manager. Its expected output proves that the inner call via this is not independently intercepted. For a database-backed service use @EnableTransactionManagement and a correctly configured manager with @Transactional on an externally invoked public service method. Test persisted state after failure; the absence of an exception alone is not evidence of commit.
Separate the inner collaborator
public class Main { interface Save { void save(); } record Checkout(Save save) { void checkout() { System.out.println("checkout"); save.save(); } } public static void main(String[] args) { Save target = () -> System.out.println("save"); Save advised = () -> { System.out.println("before save"); target.save(); }; new Checkout(advised).checkout(); }}Expected output:
checkoutbefore savesaveThe separate collaborator crosses the wrapper boundary; this models the design of two Spring beans.
Observe real Spring proxy advice
Source-reviewed, NOT RUN. File lab-fixtures/spring-v37/src/main/java/lab/spring/ProxyDemo.java; use the companion Maven lab instructions.
package lab.spring;import org.aopalliance.intercept.MethodInterceptor;import org.springframework.aop.framework.ProxyFactory;public class ProxyDemo { public interface Service { void outer(); void inner(); } public static class Target implements Service { public void outer() { System.out.println("outer"); inner(); } public void inner() { System.out.println("inner"); } } public static void main(String[] args) { var factory = new ProxyFactory(new Target()); factory.setInterfaces(Service.class); factory.setProxyTargetClass(false); factory.addAdvice((MethodInterceptor) invocation -> { System.out.println("before " + invocation.getMethod().getName()); return invocation.proceed(); }); Service service = (Service) factory.getProxy(); service.outer(); service.inner(); }}Predicted stdout:
before outerouterinnerbefore innerinnerProxyFactory creates an interface proxy; advice records only calls crossing that proxy.
Inspect declarative transaction metadata
Source-reviewed, NOT RUN. File lab-fixtures/spring-v37/src/main/java/lab/spring/TransactionDemo.java; use the companion Maven lab instructions.
package lab.spring;import org.springframework.context.annotation.*;import org.springframework.transaction.*;import org.springframework.transaction.annotation.*;import org.springframework.transaction.support.SimpleTransactionStatus;public class TransactionDemo { // Recording test double only: no resource, isolation or durability. public static class RecordingManager implements PlatformTransactionManager { public TransactionStatus getTransaction(TransactionDefinition definition) { System.out.println("begin"); return new SimpleTransactionStatus(); } public void commit(TransactionStatus status) { System.out.println("commit"); } public void rollback(TransactionStatus status) { System.out.println("rollback"); } } public static class Service { @Transactional public void work(boolean fail) { System.out.println("work"); if (fail) throw new IllegalStateException("test failure"); } } @Configuration(proxyBeanMethods=false) @EnableTransactionManagement static class Config { @Bean PlatformTransactionManager transactionManager() { return new RecordingManager(); } @Bean Service service() { return new Service(); } } public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext(Config.class)) { var service = context.getBean(Service.class); service.work(false); try { service.work(true); } catch (IllegalStateException expected) { if (!"test failure".equals(expected.getMessage())) throw expected; } } }}Predicted stdout:
beginworkcommitbeginworkrollbackThe source-reviewed fixture uses a recording PlatformTransactionManager, not a database. The test double records transaction infrastructure calls; no real commit is claimed.
Common mistakes
Do not expect @Transactional on a method called via this to start a new transaction in proxy mode. Do not infer rollback from an annotation or a logged message. Do not mark the entire application transactional to fix a missing boundary. Use real database integration tests for persistence behavior and separate external calls from local method calls.
Practice
Create a wrapper for a validation operation that records before and after messages, but propagates IllegalArgumentException from the target. Demonstrate success and failure; explain why transaction advice would need a real manager and why a caught exception might not trigger the intended rollback.
Expected output:
beforeafterbeforenegativeCompare with the manual review criteria.
Official reading: Proxy · Transactions · Rollback · Propagation. Framework execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
AOP proxies and transaction boundaries — knowledge check
Spring fundamentals and boundary reasoning.
What does a pointcut select?
Why does self-invocation bypass ordinary Spring proxy advice?
What is required for @Transactional to manage a JDBC resource?
Which exception triggers rollback by default in normal declarative configuration?
What happens to an imperative thread-bound transaction on a newly started worker thread?