
# 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](../options.md)):

| 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:

- every `@Aspect` class of the application's modules (advice and `@Pointcut` expressions);
- aspects returned by `@Bean` methods;
- advisor beans whose `@Bean` method builds `DefaultPointcutAdvisor(ExpressionPointcut('<a constant expression>'), ...)`, an `AnnotationMatchingPointcut<A>()`, or a pointcut that declares its annotations;
- the advisors of the auto-configurations. A starter's annotation pointcut declares the annotations it matches in a `static const annotationTypes` list (`@Transactional`, `@Cacheable`, method security, `@Validated`); only the beans carrying one of them keep their proxy.

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:

- a pointcut may match one of its members (by name, type, annotation, `bean(...)` with its name, aliases and qualifiers);
- its class or one of its members (or a parameter, or an overridden declaration) carries an annotation that an annotation-driven advisor matches, or a subclass of such an annotation (`class AdminTransactional extends Transactional`);
- it has a `@DeclareParents` introduction;
- its proxy mixes `ChangeNotifier` in (a `@ChangeNotifierComponent` that is not one, in Flutter apps).

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 module declares an advisor bean whose pointcut the build cannot read (an expression from a variable, a hand-written pointcut class);
- an auto-configuration declares aspects (its libraries mention `AspectMetadata`), or an advisor whose pointcut the build cannot read;
- a pointcut refers to a named pointcut the build cannot follow;
- `aop_prune: false` is set.

### 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:

```dart
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,
  ),
),
```

- `AopProxyFactory.pruned()` tells the context that the build found no advice for the bean. Its `unavailableReason` is `AopProxyFactory.prunedReason`: "the build found no pointcut of the application that matches it, so it generated no proxy class for it (set the build option aop_prune: false to generate one for every bean)." The text lives once in the runtime, not in every generated file.
- `knownAdvisors` lists the `source` of every aspect and advisor bean the build knew of. An entry without `#` stands for a whole package. The set is declared once per module.
- A subclass proxy is pruned the same way: the bean is then created as its own class (`create: (r) => Counted()`).

### 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:

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

  int count() => 0;

  String get label => '';
}
```

The proxy (simplified, prefixes dropped):

```dart
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:

```text
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:

```dart
// 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`:

```dart
// 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:

```yaml
# 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](build-conditions.md)), 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

- Keep the defaults (`aop_proxies: all`, `aop_prune: true`) for almost every application.
- Set `aop_prune: false` when advice is registered in code at run time.
- Set `aop_proxies: interfaces` to advise only through abstract types, or `none` for a module that never needs AOP.
- Set `aop_defer: true` only in a library whose modules a starter's auto-configuration imports.

## See also

- [Options](../options.md)
- [Modules left out of the build](build-conditions.md)
- [Optimizations overview](index.md)
- [Build-time checks](../checks.md)
- [Proxies](../../spring-core-dart/aop/proxies.md)
- [Pointcuts](../../spring-core-dart/aop/pointcut.md)
