AOP support in JavaConfig is a work in progress. It is documented here in order to solicit feedback. Expect changes in forthcoming milestone releases
![]() | Tip |
|---|---|
| For those unfamiliar with AOP and/or Spring AOP, you'll want to take a look Chapter 6 of the core Spring reference documentation, Aspect-oriented Programming with Spring. |
A configuration class can serve 'double duty' as an aspect. By
applying @Aspect to a
@Configuration class, you can then add
pointcuts and advice that will be applied against all beans in the
container.
@Aspect
@Configuration
public class AppConfig {
@Bean
public Service service() {
return new ServiceImpl(...);
}
@Before("execution(* service..Service+.set*(*))")
public void trackServicePropertyChange() {
logger.info("property changed on service!");
}
}
This pointcut will match the all methods starting with 'set'
on all implementations of the Service interface. Before any matching
methods execute, the
trackServicePropertyChange() method will be
executed.
To create a reusable aspect, define a class annotated with
@Configuration and
Aspect containing advice methods and
pointcuts.
@Aspect
@Configuration
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(PropertyChangeTracker.class);
@Before("execution(* set*(*))")
public void trackChange() {
logger.info("property just changed...");
}
}
Then include that aspect in the application context, either
using the @Import annotation or by adding at as a constructor argument
when instantiating
JavaConfigApplicationContext. Examples of both
approaches are below.
@Configuration
@Import(PropertyChangeTracker.class)
@Aspect // necessary in order to have transferService bean get aspects applied!
public class MyConfig {
@Bean
public TransferService myService() {
return new TransferServiceImpl(...);
}
}
...
JavaConfigApplicationContext context = new JavaConfigApplicationContext(MyConfig.class);
or...
@Aspect // necessary in order to have transferService bean get aspects applied!
@Configuration
public class MyConfig {
@Bean
public TransferService myService() {
return new TransferServiceImpl(...);
}
}
...
JavaConfigApplicationContext context =
new JavaConfigApplicationContext(MyConfig.class, PropertyChangeTracker.class);
![]() | Note |
|---|---|
Annotating Configuration classes with
|