AOP Advice on @Factory Beans

The semantics of AOP advice when applied to Bean Factories differs to regular beans, with the following rules applying:

  1. AOP advice applied at the class level of a @Factory bean will apply the advice to the factory itself and not to any beans defined with the @Bean annotation.

  2. AOP advice applied on a method annotated with a bean scope will apply the AOP advice to the bean that the factory produces.

Consider the following two examples:

AOP Advice at the type level of a @Factory

  1. @Timed
  2. @Factory
  3. public class MyFactory {
  4. @Prototype
  5. public MyBean myBean() {
  6. return new MyBean();
  7. }
  8. }

AOP Advice at the type level of a @Factory

  1. @Timed
  2. @Factory
  3. class MyFactory {
  4. @Prototype
  5. MyBean myBean() {
  6. return new MyBean()
  7. }
  8. }

AOP Advice at the type level of a @Factory

  1. @Timed
  2. @Factory
  3. open class MyFactory {
  4. @Prototype
  5. open fun myBean(): MyBean {
  6. return MyBean()
  7. }
  8. }

The above example will log the time it takes to create the MyBean bean.

Now consider this example:

AOP Advice at the method level of a @Factory

  1. @Factory
  2. public class MyFactory {
  3. @Prototype
  4. @Timed
  5. public MyBean myBean() {
  6. return new MyBean();
  7. }
  8. }

AOP Advice at the method level of a @Factory

  1. @Factory
  2. class MyFactory {
  3. @Prototype
  4. @Timed
  5. MyBean myBean() {
  6. return new MyBean()
  7. }
  8. }

AOP Advice at the method level of a @Factory

  1. @Factory
  2. open class MyFactory {
  3. @Prototype
  4. @Timed
  5. open fun myBean(): MyBean {
  6. return MyBean()
  7. }
  8. }

The above example will log the time it takes to execute all of the public methods of the MyBean bean, but not the bean creation.

The rationale for this behaviour is that you may at times wish to apply advice to a factory and at other times apply advice to the bean produced by the factory.

Note that there is currently no way to apply advice at the method level to a @Factory bean and all advice for factories must be applied at the type level. You can control which methods have advice applied by defining methods as non-public (non-public methods do not have advice applied).