AOP proxies: pruning and deferring

Spring creates AOP proxies at run time, with JDK dynamic proxies or CGLIB subclasses. Dart cannot create classes at run time, so the generator writes a proxy class for each bean that advice may need to wrap (_$OrdersProxy). The context uses that class when an advisor matches the bean, and the bean itself otherwise.

A proxy class for every bean would be a lot of code that never runs. This page explains how the generator keeps only the proxy classes, and the members of them, that the application's advice can reach.

Why

A proxy class repeats every member of its bean: each method and getter forwards to the bean through the advice chain. In an app with hundreds of beans and a handful of aspects, almost all of those classes are dead code. They make the generated files long, the compile slower and the app bigger.

The build sees every pointcut the application declares, so it can tell which beans an advice may match. It writes proxy classes for those, and for the rest a small marker that says "the build looked, and found no advice". When something the build did not see turns up at run time, the context fails at startup with a clear message instead of silently skipping the advice.

The three options

All three are set in the application's build.yaml (see Options):

Option Values Default What it decides
aop_proxies all, interfaces, none all Which beans may have a proxy class at all.
aop_prune true, false true Whether the proxy classes, and members, that no advice can match are left out.
aop_defer true, false false Whether a library package without lib/spring_auto_configuration.dart leaves its proxy classes to the application, as a starter does.

The options only change how much code is generated. At run time a bean without matching advice is never wrapped, with any setting.

aop_proxies: which beans can be proxied

Value Proxy classes
all For every bean whose class, or one of its interfaces, can be implemented: a wrapper class that implements the bean's types (class _$OrdersProxy implements Orders, ...). A class that can only be extended (it has private members, for example) gets a subclass proxy instead: the bean is created as the generated subclass.
interfaces Only through the bean's abstract supertypes, like JDK dynamic proxies. A bean without one gets no proxy.
none No proxy classes. AOP cannot advise the beans of the module.

all is like Spring's @EnableAspectJAutoProxy(proxyTargetClass = true), interfaces like proxyTargetClass = false.

aop_prune: only the proxies advice can match

With aop_prune: true (the default), the generator decides for each bean whether any advice of the application may match one of its members.

Where it prunes

Pruning needs to know all the advice of the application, so it runs only where the build can see all of it:

Output Pruned Why
The @SpringBootApplication output yes It knows every module of the application and its auto-configurations.
A @ComponentScan module of an application (a package with publish_to: none in pubspec.yaml) yes Nothing outside the application imports it. The build reads the advice of the package's other libraries in lib/ and bin/, and of the auto-configurations.
A @ComponentScan module of a library package never Any application may import it and bring aspects the library's build cannot see.
A lib/ module of a starter proxies are deferred, see below The application's build writes them.

What advice it reads

To decide, the build reads:

The pointcuts are matched with the runtime's own parser and matcher (ExpressionPointcut of spring_core_dart), so the build and the running app agree on what matches.

What keeps a proxy

A bean keeps its proxy class when:

Annotations of the SDK (@override, @Deprecated), of package:meta and of spring_core_dart keep no proxy, unless an advisor names them (AnnotationMatchingPointcut<Service>). @Validated on a @ConfigurationProperties class keeps none either: it validates the bound values once at startup, and method validation leaves such classes out, as Spring Boot does.

When nothing is pruned

Pruning needs certainty. Every bean keeps its full proxy when:

A pruned bean

A bean with no matching advice gets no proxy class and a constant marker. From a real generated file, without the import prefixes:

const _$knownAdvisors0 = {
  r'package:spring_boot_dart',
  r'package:spring_boot_starter_cache',
  r'package:spring_boot_starter_flutter',
  // ... every starter whose advisors the build read
};

// ...
BeanDefinition<AppAssets>(
  name: r'appAssets',
  source: r'package:neon_books_app/src/about/app_assets.dart#AppAssets',
  // ...
  aopProxy: const AopProxyFactory.pruned(
    knownAdvisors: _$knownAdvisors0,
  ),
),

A partial proxy: member-level forwarding

When advice may match some members of a bean but not others, the proxy class intercepts only those. Input:

@Service()
class MixedOrders {
  @Transactional()
  Future<void> place() async {}

  int count() => 0;

  String get label => '';
}

The proxy (simplified, prefixes dropped):

class _$MixedOrdersProxy with AdvisedWrapper implements MixedOrders {
  // ...
  /// place: `@Transactional()`
  @override
  Future<void> place() => this.aopInvoker.invokeAsync<void>(/* ... */);

  // Members no pointcut can match: forwarded without advice.
  @override
  int count() => this._target.count();

  @override
  String get label => this._target.label;
}

Each generated proxy class and member has a /// comment that says what the build found to run around it: the annotations an advisor matches, as written (@Transactional()); the advice of the aspects, like @Around TimingAspect.time; the advisor beans. The invoker is called with named arguments (proxy:, target:, methodIndex:, arguments:, original:), which cost nothing measurable in an AOT benchmark.

Only place has a MethodSignature in the factory. A subclass proxy does the same by overriding only the advised members; it inherits the others. The factory of a partial proxy carries knownAdvisors too.

What happens when advice the build did not see turns up

The build cannot see advice registered in code: an aspect or advisor registered by a BeanDefinitionRegistrar, a BeanFactoryPostProcessor or registerSingleton. With a pruned or partial proxy, that advice could not reach the members the build left out. So the context checks at startup, before it creates the singletons, and fails:

The advisor bean 'audit' (registered in code) is not one the build knew of
when it generated the proxies of the beans for only the advice it found (bean
'mixedOrders' and maybe others): its advice would not reach the members left
out. Build the application with the option aop_prune: false, or declare the
advice where the build reads it (an @Aspect, or a @Bean method returning a
DefaultPointcutAdvisor with a constant pointcut).

Advised.addAdvisor on a partial proxy fails for the same reason. Build with aop_prune: false when the application adds advice at run time.

Deferred proxies: starters leave them to the application

A starter's build cannot know the aspects of the applications that will use it. Writing a proxy class for every starter bean "just in case" would put that code into every app. So the lib/ modules of a starter (a package with lib/spring_auto_configuration.dart) write a placeholder instead, for each bean that only an application's aspect could match:

// spring_boot_dart/lib/spring_gen/src/properties/properties.spring.dart
// (generated; prefixes dropped)
BeanDefinition<MainProperties>(
  name: r'mainProperties',
  source: r'package:spring_boot_dart/src/properties/boot_properties.dart#MainProperties',
  create: (r) => MainProperties(),
  annotations: const [ConfigurationProperties(r'spring.main')],
  aopProxy: const AopProxyFactory.deferred(
    signatures: [
      MethodSignature.of(
        r'allowBeanDefinitionOverriding',
        _$target0,
        kind: MemberKind.getter,
        returnType: r'bool',
      ),
      // ... one signature per member
    ],
  ),
),

A bean is deferred only when nothing of the starter itself could advise it: its annotations, and those of its members and parameters, are ones no advisor matches (the SDK's, package:meta's, spring_core_dart's or spring_boot_dart's, @Validated excepted), no pointcut of the starter's own packages matches it, it is a wrapper (not a subclass proxy) and it has no introduction. A starter whose modules declare advisor beans, or whose auto-configurations declare aspects or advisors the build cannot read, defers nothing.

The application writes them

The @SpringBootApplication output looks for these placeholders in the generated modules that the auto-configuration libraries and the application's own libraries reach, through the libraries they import or export, in any package. For each such bean whose members one of the application's pointcuts may match, it writes the proxy class and registers its factory under the bean's source:

// bin/spring_gen/main.spring.dart (generated; prefixes dropped, factory shortened)
class _$BannerPropertiesProxy with AdvisedWrapper implements BannerProperties {
  // ...
}

BeanModule get $application => BeanModule(
  r'application',
  [/* the application's beans */],
  aopProxies: {
    r'package:spring_boot_dart/src/properties/boot_properties.dart#BannerProperties':
        AopProxyFactory(
          signatures: const [/* ... */],
          create: (target, invoker) =>
              _$BannerPropertiesProxy(target as BannerProperties, invoker),
        ),
  },
);

The context puts that factory in the placeholder's place, whichever module is loaded first. A deferred bean no pointcut matches gets nothing in the application. With aop_prune: false, the application writes the proxy of every deferred bean. With aop_proxies: none it writes none.

A context built without the application's generated module (an ApplicationContextRunner, a hand-written list of modules) has no proxy class for a deferred bean. Advice that matches it then fails the startup with AopProxyFactory.deferredReason, which says to build the application with its @SpringBootApplication, use aop_prune: false, or declare the bean with a @Bean method.

aop_defer: a library a starter imports

A library package without lib/spring_auto_configuration.dart keeps every proxy by default: any module may import it. Some libraries are always reached through a starter's auto-configuration; spring_boot_actuator is one (the actuator starter's auto-configuration imports it). Such a library sets aop_defer: true, and its lib/ modules defer like a starter's:

# build.yaml of spring_boot_actuator
targets:
  $default:
    builders:
      spring_core_dart_generator:spring_core_dart:
        enabled: false
      spring_core_dart_generator:spring_properties:
        enabled: true
        generate_for: [lib/src/properties/**]
        options:
          aop_defer: true

For spring_boot_actuator this took its generated module from 2083 to 1420 lines. Deferring needs aop_prune to be true in the library's build.

Deferred proxies follow build conditions

When a starter module is left out of the build by a property (see Modules left out of the build), the proxies of its beans go with it:

The deferred bean is defined by In the application
only modules decided never no proxy class, no aopProxies entry, no import
only modules decided notInRelease the aopProxies entry under if (!const bool.fromEnvironment('dart.vm.product')), so a release removes the class
at least one module that is always in the proxy as usual

Choosing the options

See also