The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Spring
AOP and proxies
What is a proxy, and how does Spring step in before and after my method?
Why it exists — If tasks such as starting and committing a transaction, or writing logs, are written by hand in every method, the same lines are scattered in many places, and when one is forgotten or needs changing, you have to hunt through all of them. Spring keeps that work outside the body of the method, and a proxy registered in place of the bean receives the call first and inserts that work before and after it, so the code of the original method is left untouched.
Where it's used today — Spring annotations such as @Transactional (wrapping a method in a transaction), @Cacheable (returning a stored result), and @Async (running in another thread) work through this proxy. If you put an annotation on and it does not work, first check whether the class name of the object you called has $SpringCGLIB$ in it, and whether you are calling an object made directly with new. If you want to insert something of your own, you make an aspect class with @Aspect and use it for things such as measuring execution time or recording calls.
When you put @Transactional on a method, starting and ending a transaction happens when you call that method, even though we did not write it. This is because Spring does not use the object of the class we wrote as the bean as it is. It creates a stand-in object (a proxy) that receives the calls in its place, and keeps that as the bean. Keeping the work that many methods need in common (transactions, logs, and so on) outside the body of the method and inserting it before and after the call like this is called AOP. OrderService and Caller on the screen are class names made up for this lab as examples, and @Service, @Component, @Autowired, @Transactional, and the class TransactionSynchronizationManager are provided by Spring. TransactionSynchronizationManager.isActualTransactionActive() returns true if a transaction is in progress at the time that line runs. If @Autowired is on the orderService field of the calling class Caller, Spring makes that field refer to the OrderService bean that it keeps. In this lab you remove @Transactional or make that field refer to an object made directly with new OrderService(), and see which lines order() prints and what the class name of the object you called is. Instead of @Transactional, which Spring provides, you can also insert a class that we make ourselves with @Aspect (LogAspect, a name made up for this example).
Checked against real execution · Ran all six combinations on Spring 7.0.9, H2 2.4.240, and AspectJ weaver 1.9.25.1 with a real @Transactional proxy (transaction manager plus H2) and a real @Aspect proxy, and checked the printed lines, the class of the called object, and the number and order of transaction starts and commits
Concepts in this lab
- Proxy
- This is a stand-in object that receives calls in place of the real object. When it receives a call, it does some additional work and then passes the call on to the real object. Spring wraps a bean that needs a feature such as AOP or @Transactional in such an object and registers it in the container, so what other beans receive by injection is this stand-in, not the real object.
- Aspect-oriented programming (AOP)
- This programming technique separates additional behavior that appears repeatedly in many places (crosscutting concerns), such as logging, transactions, and permission checks, from the core business code and gathers it in one place. You write the additional behavior only once and specify separately "where to apply it", so the core code stays clean and a change to that behavior is made in one place.
- @Transactional
- This annotation is placed on a method or a class so that its scope runs as one transaction. The proxy starts a transaction before the method runs, commits if the method ends normally, and rolls back according to the rules if an exception occurs. You do not have to write the code that starts and ends the transaction yourself, so this is called a declarative transaction.
- TransactionSynchronizationManager
- Why it exists — The side that starts a transaction (the proxy and the transaction manager) and the side that uses the database (JdbcTemplate, JPA, and so on) are different objects, so for the two to use the same database connection in the same transaction, there had to be a place to record the transaction state of the current thread.
- Where it's used today — You rarely call it directly in business code. In tests or debugging, you print isActualTransactionActive() to check whether @Transactional really took effect (whether the call went through the proxy).
- TransactionSynchronizationManager is a class provided by Spring (in the org.springframework.transaction.support package) that records, for each thread, the resources used by a transaction (such as a database connection) and the state of the transaction. Its static method isActualTransactionActive() returns true if an actual transaction is in progress in the thread that runs this line now, and false otherwise. A transaction manager (for example DataSourceTransactionManager) records this state when it starts a transaction, and clears it when it ends the transaction. The Spring API documentation says that this class is meant to be used by code that manages resources, and not by ordinary application code.
- @Autowired
- Why it exists — If you write in a configuration file, one by one, which bean to put in which place, the configuration file has to be changed together every time you change a class. With @Autowired, you only mark the place that receives it, and Spring looks at the type, picks the matching bean, and puts it in.
- Where it's used today — In old code and test code, you often see it put on a field. Newly written code more often receives beans through a constructor instead of a field.
- @Autowired is an annotation that you put on a field or a constructor so that Spring finds a bean of the matching type in the container and puts it in that place. When it is put on a field, Spring fills in the object even if our code has no line that puts a value in the field. If there is no matching bean, the injection fails by default. Spring looks in the beans kept by the container, so an object made directly with new in the code is a different object from the bean the container kept.
- @Aspect and @Before
- Why it exists — If the work to be inserted and its targets are written separately in a configuration file, it is hard to tell from the code alone what is inserted and when. @Aspect and @Before let you write that directly on the class and method, so that by looking at one class you can tell what runs and when.
- Where it's used today — It is used to leave a record every time a method is called, or to check the values passed in before execution. For work to do after a method ends, use @After or @AfterReturning instead, and for work before and after, use @Around.
- @Aspect is an annotation that you put above a class to mark that the class is an aspect (a class where behavior to insert into many methods in common is written). An aspect also has to be a bean managed by Spring, so to have it found by class path scanning, @Aspect alone is not enough, and you must also add an annotation such as @Component. @Before is put above a method of the aspect, and a pointcut expression is written in its parentheses. This method runs before the method that the expression selects runs. When Spring decides that an aspect applies to a bean, it creates a proxy of that bean automatically (auto-proxying). To use this feature, you must turn on @AspectJ support, and the aspectjweaver library must be on the class path.
Try these
- Default settings — Spring kept a proxy (OrderService$SpringCGLIB$0) as the bean instead of OrderService, and the proxy receives the call first, starts a transaction, and then calls order(). The transaction that order() saw is active (true).
- Removing @Transactional — There is nothing to insert, so Spring does not create a proxy. The object you called is OrderService as it is, and no transaction is active (false).
- Calling an object made with new — Spring created and kept a proxy, but what you called is the object we made directly, so the call does not go through the proxy. Even with @Transactional, no transaction is started (false).
- Inserting an aspect we make ourselves — If the aspect we made selects order(), Spring creates a proxy in the same way. The proxy prints the [log] line first and then calls order(). No transaction is started (false).
Running with the default settings
- When the program starts, Spring finds the classes with @Service or @Component (component scanning), creates an object of each, and keeps it. An object that Spring creates and keeps like this is called a bean. Spring also creates one object of the OrderService class. It also creates the transaction manager written in the configuration class that the screen leaves out (DataSourceTransactionManager, provided by Spring, connected to an H2 database) as a bean.
- Spring sees that @Transactional is on order() of OrderService. So it does not use the OrderService object it just created as the bean as it is. It creates a stand-in object (a proxy) that receives the calls in place of that object, and keeps it as the OrderService bean. The proxy is an object of the class OrderService$SpringCGLIB$0, which Spring made while the program was running. This class extends OrderService, and the proxy holds a reference to the real OrderService object. The two are different objects. Neither this class nor the line that creates the proxy is in the code we wrote.
- Spring also creates an object of the Caller class, which has @Component. The orderService field has @Autowired, so Spring looks for a bean of the type OrderService and makes this field refer to that bean. We did not write a line that assigns a value to this field. What this field refers to now is the proxy that Spring kept.
- run() of Caller calls orderService.order(). What the orderService field refers to is the proxy, so the call arrives first at the proxy, not at the real OrderService. The proxy knows that @Transactional is on order().
- Before it calls the real order(), the proxy has the transaction manager start a transaction. The transaction manager takes one connection to the H2 database and starts a transaction. The line that does this work is not in order().
- The proxy calls order() of the real OrderService object that it holds a reference to. order() asks with isActualTransactionActive() whether a transaction is in progress now, gets true, and prints "Transaction active: true".
- When order() ends without an exception and control returns to the proxy, the proxy has the transaction manager commit. The transaction ends here. If order() had ended with a runtime exception, it would roll back instead of committing.
- The next line of run() prints the class name of the object the orderService field refers to (getClass() and getSimpleName() are methods provided by Java). The printed name is "OrderService$SpringCGLIB$0". It is not the OrderService we wrote but a proxy class that Spring made. The $SpringCGLIB$ in the middle of the name is a mark that Spring puts on a class it made with a library called CGLIB.
Result of this run
- Spring did not use the OrderService that has @Transactional as the bean as it is. It created a proxy that extends OrderService (class OrderService$SpringCGLIB$0) and kept it as the bean. When order() was called, the proxy received the call first, started a transaction, called the real order(), and then committed. So when order() asked, a transaction was active (true).
- There is no line in order() that starts or commits a transaction. Keeping work that is needed in common outside the method and inserting it before and after the call like this is AOP, and what inserts it is the proxy.
Code
// … The configuration class (@EnableTransactionManagement, an H2 DataSource, a transaction manager bean) and the import lines are left out
@Service
class OrderService {
// An annotation provided by Spring: wraps this method in a transaction
@Transactional
public void order() {
// A method provided by Spring: returns true if a transaction is in progress now
boolean active = TransactionSynchronizationManager.isActualTransactionActive();
System.out.println("Transaction active: " + active);
}
}
@Component
class Caller {
// Makes this field refer to the OrderService bean that Spring keeps
@Autowired
OrderService orderService;
void run() {
orderService.order();
System.out.println(orderService.getClass().getSimpleName());
}
}
Assumptions of this model
Checked against Spring Framework 7.0.9 (AspectJ weaver 1.9.25.1), H2 2.4.240, and HikariCP 7.0.2 running on JDK 21 with AnnotationConfigApplicationContext. All six combinations (@Transactional, nothing, LogAspect × the bean received with @Autowired, the object made with new) were checked by compiling the same source as the code on the screen (with only the package and import lines added) and starting a new child Java process for each combination. The configuration class that the screen leaves out had @EnableTransactionManagement, @EnableAspectJAutoProxy, @ComponentScan, a DataSource connected to an H2 in-memory database, and a DataSourceTransactionManager bean (to the transaction manager I added only lines that count the number and the order of starts, commits, and rollbacks). In Spring Boot, auto-configuration does this setup for you, but this lab was not run with Boot. What was checked is the lines that run() printed and their order, the class name of the called object and whether it is a proxy as measured with AopUtils, the class of the OrderService bean taken from the container and whether it is a proxy, whether the called object and that bean are the same object, the number of proxies in the container, and the number of times the transaction manager started and committed a transaction and their order (start, "Transaction active: true", commit). The facts that the step sentences rely on were also checked by execution: that the proxy is a class that extends OrderService and holds a reference to one real OrderService object, that the database connected when the transaction starts is H2, and that an object made with new is different from that bean and is not a proxy. The proxy class name OrderService$SpringCGLIB$0 is the name that was actually printed in this checking run. What the documentation defines comes from the section Using @Transactional in Data Access of the Spring Framework 7.0 documentation (that with the default proxy mode only an external call that comes in through the proxy is intercepted, and that by default it rolls back on RuntimeException and Error), the section AOP Proxies in Core (that an object without an interface is proxied with CGLIB), the section Understanding AOP Proxies (that the advice runs only when the call reaches the proxy), the section Declaring an Aspect (that @Aspect alone is not picked up by scanning and @Component is needed), and the API documentation of TransactionSynchronizationManager (that isActualTransactionActive() returns whether an actual transaction is active in the current thread, and that this class is meant to be used by code that manages resources, not by ordinary application code). The sentence "if it ends with a runtime exception, it rolls back" was not run in this lab, and relies on the documentation and on the results of running the lab "@Transactional". OrderService in this lab is a class without an interface, so a CGLIB proxy was created. This lab does not cover a class that implements an interface, where a JDK dynamic proxy may be used, a call made inside the same class (self-invocation), or using @Transactional and an aspect together, and the diagram is simplified to show only the code on the screen. What commits and rollbacks leave in the database is covered in the lab "@Transactional", the time when @Before runs and the rules of pointcut expressions are covered in the lab "AOP: advice and pointcuts", and self-invocation and the proxy types (JDK dynamic proxy, CGLIB) are covered in the lab "Proxies and self-invocation".
Previous lab: Dependency injection · Next lab: Servlets