
# Bean definitions

For every bean it finds, the generator writes one `BeanDefinition<T>` into the `.spring.dart` file. A bean is a `@Component` class (or a class with `@Service`, `@Repository`, `@Controller`, `@Configuration` and the other annotations that extend `@Component`), or a `@Bean` method. The definition is the recipe the container follows: the bean's name, the types it can be found by, its flags, and closures that create it, inject it, initialize it and destroy it.

This page shows what goes into each field, and which annotation puts it there. The examples come from real generated files. They are simplified: the real files use import prefixes (`_i1.BeanDefinition`, `_i2.Greeter`), which are dropped here, and long `source` strings are shortened.

## Why

Spring reads annotations and calls constructors with reflection when the context starts. Dart has no reflection in Flutter, in AOT executables or on the web, so the generator does that work at build time. It reads each class with the analyzer and writes plain Dart: a constructor call in a closure, a method call for each `@PostConstruct`, an assignment for each `@Autowired` field.

So the container never looks anything up by name in a class. It only calls closures that the compiler has checked. That is why the code works the same on the Dart VM, in AOT, in Flutter and on the web, and why minification and tree shaking do not break it.

## A first example

```dart
// You write (example/main.dart):
@Component()
class EnglishGreeter implements Greeter {
  EnglishGreeter(@Value(r'${greeting.punctuation:!}') this.punctuation);

  final String punctuation;

  @override
  String greet(String name) => 'Hello, $name$punctuation';
}

@Service()
class Registration {
  Registration(this.greeter, this.events);

  final Greeter greeter;
  final ApplicationEventPublisher events;
}
```

```dart
// The generator writes (example/spring_gen/main.spring.dart, simplified):
BeanDefinition<EnglishGreeter>(
  name: r'englishGreeter',
  source: r'asset:spring_core_dart/example/main.dart#EnglishGreeter',
  types: const [EnglishGreeter, Greeter],
  dependencies: const [Dependency.value(r'${greeting.punctuation:!}')],
  create: (r) =>
      EnglishGreeter(r.value<String>(r'${greeting.punctuation:!}')),
  annotations: const [Component()],
  aopProxy: const AopProxyFactory.pruned(knownAdvisors: _$knownAdvisors0),
),
BeanDefinition<Registration>(
  name: r'registration',
  source: r'asset:spring_core_dart/example/main.dart#Registration',
  dependencies: const [
    Dependency(Greeter, name: r'greeter'),
    Dependency(ApplicationEventPublisher, name: r'events'),
  ],
  create: (r) => Registration(
    r.dependency<Greeter>(name: r'greeter'),
    r.dependency<ApplicationEventPublisher>(name: r'events'),
  ),
  annotations: const [Service()],
  aopProxy: const AopProxyFactory.pruned(knownAdvisors: _$knownAdvisors0),
),
```

`r` is the container's `DependencyResolver`. `Registration` has no `types:` line, because it is found only by its own type, which is the default. An optional field is written only when it differs from the runtime's default, so the output stays short.

## The fields at a glance

| Field | Comes from | Written when |
|---|---|---|
| `name` | the class name in lower camel case, `@Component('name')`, the `@Bean` method name or `@Bean(name:)` | always |
| `source` | the library URI and the class (and method) name | always |
| `types` | the class (or the type a `@Bean` method returns) and its public supertypes | when there is more than the bean's own type |
| `factoryObjectTypes` | the product type of a `FactoryBean<T>` | for a `FactoryBean` |
| `aliases` | `@Bean(aliases: [...])` | when there are aliases |
| `scope` | `@Scope('...')` | when not `singleton` |
| `scopedProxy` | `@Scope(proxyMode: ...)` | for a scoped proxy |
| `lazy` | `@Lazy()`, `@ComponentScan(lazyInit: true)` | when `true` |
| `primary` | `@Primary()` | when `true` |
| `fallback` | `@Fallback()` | when `true` |
| `autowireCandidate` | `@Bean(autowireCandidate: false)` | when `false` |
| `defaultCandidate` | `@Bean(defaultCandidate: false)` | when `false` |
| `factoryBeanName`, `factoryMethodName` | the class and method of a `@Bean` method | for a `@Bean` method (no `factoryBeanName` for a static one) |
| `order` | `@Order(n)` | when set |
| `description` | `@Description('...')` | when set |
| `dependsOn` | `@DependsOn([...])` | when set |
| `qualifiers` | `@Qualifier('...')` on the class or `@Bean` method | when set |
| `conditions` | `@Profile`, `@Conditional`, condition annotations such as `@ConditionalOnProperty` | when there are conditions |
| `dependencies` | every injection point | when there are any |
| `create` | the constructor, or the `@Bean` method | always |
| `inject` | `@Autowired` and `@Value` fields and setters, `@Autowired` methods, `@Resource` | when there are any |
| `postConstruct`, `preDestroy` | `@PostConstruct`, `@PreDestroy` methods | when there are any |
| `initMethod`, `initMethodName` | `@Bean(initMethod:)` | when set |
| `destroyMethod`, `destroyMethodName` | `@Bean(destroyMethod:)`, or a `close`, `shutdown` or `dispose` method found by name | when there is one |
| `eventListeners` | `@EventListener` methods, `ApplicationListener<E>` | when there are any |
| `annotatedMethods` | methods with an annotation marked `@BeanMethodAnnotation()`, such as `@Scheduled` | when there are any |
| `annotations` | the annotations of the class (for a `@Bean` method: of the method, then of the returned class) | when there are any |
| `aopProxy` | the generated AOP proxy, or why there is none | when the bean can be proxied |
| `aspect` | the advice of an `@Aspect` class | for an aspect |

The sections below explain each group.

## Name and source

The default name follows Spring's rule: the first letter of the class name in lower case (`AuthService` becomes `authService`), except when the first two letters are capitals (`URLService` stays `URLService`). A `@Bean` method's bean is named after the method.

```dart
@Component('offline')       // name: r'offline'
@Fallback()
class OfflineGateway implements PaymentGateway { ... }
```

An explicit name that is empty, blank, or starts or ends with a space fails the build. Two beans without conditions that share a name or an alias also fail the build, with both declarations named. Beans with conditions may share a name (a `dataSource` for `@Profile(['dev'])` and one for `@Profile(['prod'])`); the container checks a real clash when it starts.

`source` says where the bean is declared: `package:app/src/shop/payments.dart#OfflineGateway`, or `...#ShopConfig.clock` for a `@Bean` method. A file outside `lib/` has an `asset:` URI. The container uses it in error messages, and it ignores a definition registered again with the same name and the same source, so a module imported twice does no harm.

## Types

Dart cannot ask at run time whether one `Type` is a subtype of another. So the definition lists every type the bean can be injected by: its class and every public supertype except `Object`.

```dart
@Component()
class ShippingNotifier implements ApplicationListener<OrderShipped> { ... }

// Generated:
types: const [
  ShippingNotifier,
  ApplicationListener<OrderShipped>,
  ApplicationListener<Object>,
],
```

A generic type is also listed in its raw form, with its type arguments set to their bounds (`ApplicationListener<Object>` above, `Store<dynamic>` for `Store<User>`). So a `List<Store>` gets every store, like a raw type in Spring. A private supertype is left out, because generated code cannot name it, and so is an SDK type that no public library exports.

A generic bean class is registered under its raw type.

## Scope, laziness and candidate flags

```dart
@Configuration()
class ShopConfig {
  @Bean(name: 'coverStore', aliases: ['covers'], initMethod: 'open')
  @Lazy()
  CoverStore coverStore(
    @Value(r'${neon.covers.directory:build/covers}') String directory,
    ResourceLoader resources,
  ) => CoverStore(directory, resources);

  @Bean()
  @Scope(ScopeType.prototype)
  ReceiptBuilder receiptBuilder(ShopProperties shop) =>
      ReceiptBuilder(shop.name, clock().now());
}
```

```dart
// Generated (simplified):
BeanDefinition<CoverStore>(
  name: r'coverStore',
  source: r'package:neon_books_server/src/shop/shop_config.dart#ShopConfig.coverStore',
  aliases: const [r'covers'],
  lazy: true,
  factoryBeanName: r'shopConfig',
  factoryMethodName: r'coverStore',
  dependencies: const [
    Dependency(ShopConfig, qualifier: r'shopConfig'),
    Dependency.value(r'${neon.covers.directory:build/covers}'),
    Dependency(ResourceLoader, name: r'resources'),
  ],
  create: (r) => (r.dependency<ShopConfig>(qualifier: r'shopConfig')
      as _$ShopConfigConfiguration)._$coverStore(r),
  initMethod: (bean) {
    bean.open();
  },
  initMethodName: r'open',
  destroyMethod: (bean) {
    bean.close();
  },
  destroyMethodName: r'(inferred)',
  // ...
),
BeanDefinition<ReceiptBuilder>(
  name: r'receiptBuilder',
  scope: r'prototype',
  factoryBeanName: r'shopConfig',
  factoryMethodName: r'receiptBuilder',
  // ...
),
```

- `scope` is the `@Scope` value: `prototype`, or the name of a custom scope (`@Scope('import-batch')` gives `scope: r'import-batch'`). With `@Scope(proxyMode: ...)` the generator also writes `scopedProxy:`, a generated class that finds the current instance of the scope on every call, so a singleton can hold a request- or session-scoped bean. A `proxyMode` on a singleton, or on a `FactoryBean`, fails the build.
- `lazy` is `true` with `@Lazy()`. On a `@Bean` method, `@Lazy(false)` wins over `@Lazy()` on its class, which wins over `@ComponentScan(lazyInit: true)`.
- `primary` and `fallback` come from `@Primary()` and `@Fallback()`.
- `autowireCandidate: false` and `defaultCandidate: false` come from the `@Bean` options of the same name.

## Order, description, depends-on and qualifiers

```dart
@Component()
@Order(1)
class BulkDiscount implements PriceRule { ... }

// Generated:
BeanDefinition<BulkDiscount>(
  name: r'bulkDiscount',
  types: const [BulkDiscount, PriceRule],
  order: 1,
  create: (r) => BulkDiscount(),
  annotations: const [Component(), Order(1)],
  // ...
),
```

- `order` is the `@Order` value of the class, or of the `@Bean` method. It sorts the bean in injected lists.
- `description` is the `@Description` text.
- `dependsOn` lists the names of `@DependsOn([...])`: beans created before this one and destroyed after it.
- `qualifiers` holds the `@Qualifier('...')` values declared on the class or the `@Bean` method. A qualified injection point selects the bean by these values, by its name or by an alias.

## Conditions

Three kinds of annotations become conditions:

- `@Profile([...])`, or an annotation class that extends `Profile`, becomes a `const ProfileCondition([...])`;
- `@Conditional([MyCondition])` (or a subclass) becomes `MyCondition()`. The type must implement `Condition` and have a constructor without required parameters, or the build fails;
- any other constant annotation whose class implements `Condition`, such as `@ConditionalOnProperty` or `@ConditionalOnMissingBean`, is written again as the same constant.

The conditions of a class are wrapped in one `ConditionGroup` keyed by the class. The same group guards the class's `@Bean` methods, the classes it `@Import`s and its `@PropertySource`s, so they are decided once, all or nothing, as Spring decides per class.

```dart
@Component()
@ConditionalOnProperty('neon.support.bot.enabled', havingValue: 'true')
class SupportBot { ... }

// Generated:
conditions: [
  ConditionGroup(
    r'package:neon_books_server/src/support/support_bot.dart#SupportBot',
    [
      const ConditionalOnProperty(
        r'neon.support.bot.enabled',
        havingValue: r'true',
      ),
    ],
  ),
],
```

A `@Bean` method gets its class's group first, then its own conditions, without a group:

```dart
@Bean()
@ConditionalOnMissingBean(Clock)
Clock clock() => const SystemClock();

// Generated (the class has no conditions):
conditions: [const ConditionalOnMissingBean(Clock)],
```

A meta-annotation works too. In the server guide, `@AdvancedTour()` is an annotation that extends `Profile`, and every class that carries it gets `ConditionGroup(..., [const ProfileCondition([r'advanced'])])`.

## Creation: `create`

`create` is a closure that returns a new instance. For a class it calls the constructor, with each argument taken from `r`.

The generator picks the constructor like Spring does:

- a constructor with `@Autowired()` (only one may have it);
- several `@Autowired(required: false)` constructors: the generated code calls the first one, greediest first, whose required beans exist (it tests them with `r.containsBeanOfType`), else the last one;
- otherwise the only public constructor, the primary constructor, or the one that takes no arguments. Anything else is ambiguous and fails the build.

How each parameter is read:

| Parameter | Dependency | Call in `create` |
|---|---|---|
| `Clock clock` | `Dependency(Clock, name: r'clock')` | `r.dependency<Clock>(name: r'clock')` |
| `Clock? clock` | `Dependency(Clock, optional: true, name: r'clock')` | `r.optionalDependency<Clock>(name: r'clock')` |
| `@Qualifier('offline') PaymentGateway backup` | `Dependency(PaymentGateway, qualifier: r'offline', name: r'backup')` | `r.dependency<PaymentGateway>(qualifier: r'offline', name: r'backup')` |
| `List<PriceRule> rules` | `Dependency.collection(PriceRule, optional: true)` | `r.optionalDependencyList<PriceRule>() ?? <PriceRule>[]` |
| `Map<String, PriceRule> byName` | `Dependency.map(PriceRule, optional: true)` | `r.optionalDependencyMap<PriceRule>() ?? <String, PriceRule>{}` |
| `ObjectProvider<ImportBatch> batch` | `Dependency.provider(ImportBatch, name: r'batch')` | `r.provider<ImportBatch>(name: r'batch')` |
| `@Lazy() Catalog self` | `Dependency.lazy(Catalog, name: r'self')` | `_$CatalogLazy(r.lazyDependency<Catalog>(name: r'self'))` |
| `@Value(r'${a.b}') int size` | `Dependency.value(r'${a.b}')` | `r.value<int>(r'${a.b}')` |

The parameter name is passed as `name:`: among several beans of the type, the one with that name or alias wins. A `Set` is built from the map lookup, so it keeps registration order; only lists are sorted. `ObjectFactory<T>` and the Jakarta `Provider<T>` get the same provider as `ObjectProvider<T>`. A `Map` must have `String` keys (the bean names).

A list, set or map parameter of a constructor or `@Bean` method resolves to an empty collection when no bean matches, as the table shows. A parameter with a Dart default value is optional, and the default is applied with `??`:

```dart
OrderService(
  this._orders, {
  @Value(r'${neon.orders.shipping-delay:5s}')
  this.shippingDelay = const Duration(seconds: 5),
});

// Generated, in create:
shippingDelay:
    r.optionalValue<Duration>(r'${neon.orders.shipping-delay:5s}') ??
    const Duration(seconds: 5),
```

A `@Value` expression can be a placeholder (`${...}`), a SpEL expression (`#{...}`) or a resource location (`resources:templates/mail.txt` read into a `Resource`). The generator writes the expression as it is; the runtime resolves it and converts it to the parameter's type. See [@Value](../spring-core-dart/config/value.md).

## Dependencies

`dependencies` describes every injection point of the bean: the constructor's, the fields', the setters' and the `@Autowired` methods'. The container does not use it to look beans up; `create` and `inject` do that. It uses it to check the whole graph when the context starts, before any bean is created: a missing bean, two candidates that cannot be told apart, or a cycle stop the start with a report.

For an instance `@Bean` method, the first dependency is the class that declares it, by its bean name, so the container creates it first:

```dart
dependencies: const [
  Dependency(ShopConfig, qualifier: r'shopConfig'),
  Dependency(ShopProperties, name: r'shop'),
],
```

When a bean has several `@Autowired(required: false)` constructors, every point is marked optional here, because no single one is required.

## Fields, setters and methods: `inject`

`@Autowired`, `@Inject`, `@Value` and `@Resource` on fields and setters, and `@Autowired` on methods, go into one `inject` closure. The container runs it right after `create`.

```dart
@Service()
class OrderService {
  OrderService(this._orders);

  final OrderRepository _orders;

  @Autowired()
  late final Checkout checkout;      // field injection

  late Clock _clock;

  @Autowired()
  set clock(Clock clock) => _clock = clock;   // setter injection
}

@Component()
class StartupAnnouncement implements CommandLineRunner {
  @Value('#{shopProperties.name.toUpperCase()}')
  late final String banner;

  @Autowired()
  void configure(Environment environment, ApplicationContext context) { ... }
}
```

```dart
// Generated (simplified):
// OrderService
inject: (bean, r) {
  bean.checkout = r.dependency<Checkout>(name: r'checkout');
  bean.clock = r.dependency<Clock>(name: r'clock');
},

// StartupAnnouncement
inject: (bean, r) {
  bean.banner = r.value<String>(r'#{shopProperties.name.toUpperCase()}');
  bean.configure(
    r.dependency<Environment>(name: r'environment'),
    r.dependency<ApplicationContext>(name: r'context'),
  );
},
```

The order is Spring's: superclass members first, and in each class the fields, then the setters and methods. A field with a nullable type is optional: when no bean is found it is left alone (`if (r.optionalDependency<T>(...) case final value?) { bean.x = value; }`), so it keeps its initializer.

These mistakes fail the build:

- an injected field that cannot be set: declare it `late final` or non-final;
- a private field, setter or method: the generated file is another library and cannot reach it. Inject it through a constructor parameter instead (`this._clock` keeps the field private);
- `@Autowired(required: false)` on a field, setter or method: `required` only chooses among constructors. Use a nullable type for an optional dependency;
- `@Resource` together with `@Autowired`, `@Inject` or `@Value`;
- an `async` `@Autowired` method, which the generated code would not await.

A field declared by a primary constructor parameter is injected through the constructor, not as a field. See [@Autowired](../spring-core-dart/beans/autowired.md).

## Lifecycle callbacks

```dart
class LifecycleProbe implements InitializingBean, DisposableBean {
  @PostConstruct()
  void postConstruct() { ... }

  @PreDestroy()
  void preDestroy() { ... }

  void customInit() { ... }
  void customDestroy() { ... }
  // afterPropertiesSet() and destroy() of the interfaces ...
}

@Configuration()
class LifecycleConfig {
  @Bean(initMethod: 'customInit', destroyMethod: 'customDestroy')
  LifecycleProbe lifecycleProbe() => LifecycleProbe();
}
```

```dart
// Generated (simplified):
postConstruct: (bean) {
  bean.postConstruct();
},
initMethod: (bean) {
  bean.customInit();
},
initMethodName: r'customInit',
preDestroy: (bean) {
  bean.preDestroy();
},
destroyMethod: (bean) {
  bean.customDestroy();
},
destroyMethodName: r'customDestroy',
```

- `postConstruct` calls every `@PostConstruct` method, superclass methods first. `preDestroy` calls every `@PreDestroy` method, subclass methods first.
- `initMethod` and `destroyMethod` come from `@Bean(initMethod:, destroyMethod:)`. The method must exist on the returned type and take no required arguments.
- `@Bean`'s `destroyMethod` defaults to `'(inferred)'`, as in Spring: the generator looks for a public `close`, `shutdown` or `dispose` method without required parameters, and writes `destroyMethodName: r'(inferred)'` when it finds one (the `coverStore` bean above). `destroyMethod: ''` turns this off.
- A method that is both annotated and named as the init or destroy method runs once.
- A lifecycle method that returns a `Future` is written as an `async` closure that awaits it (`(bean) async { await bean.open(); }`). `refreshAsync()` and `closeAsync()` await that future.
- `InitializingBean.afterPropertiesSet` and `DisposableBean.destroy` need nothing in the definition: the container calls them because the bean implements the interface.

When the context creates a bean it calls, in order: `create`, `inject`, the aware callbacks, `postProcessBeforeInitialization`, `postConstruct`, `afterPropertiesSet`, `initMethod`, `postProcessAfterInitialization`. On close: the `DestructionAwareBeanPostProcessor`s, `preDestroy`, `DisposableBean.destroy`, `destroyMethod`. See [Lifecycle](../spring-core-dart/beans/lifecycle.md).

## Event listeners

Each `@EventListener` method, and the `onApplicationEvent` of an `ApplicationListener<E>`, becomes an `EventListenerMethod` with a closure that calls it:

```dart
bool isVipOrder(OrderPlaced placed) => placed.order.total >= 100;

@Component()
class VipDesk {
  @EventListener(condition: isVipOrder)
  @Order(2)
  void onVipOrder(OrderPlaced placed) { ... }
}
```

```dart
// Generated:
eventListeners: [
  EventListenerMethod.of<VipDesk, OrderPlaced>(
    r'VipDesk.onVipOrder',
    (bean, event) {
      bean.onVipOrder(event);
      return null;
    },
    order: 2,
    condition: isVipOrder,
  ),
],
```

The first argument is the listener's id. `@Async()` on the method adds `async: const Async()`. A method that returns a value returns it from the closure, so the runtime can publish it as a new event. A listener of `PayloadApplicationEvent<P>` is written with `EventListenerMethod.forPayload`, and one with several event types (`@EventListener(classes: [A, B])`) with `EventListenerMethod.matching`, which tests the event's type.

The condition is a function, not a SpEL string: Dart cannot evaluate a string against an object without reflection. See [@EventListener](../spring-core-dart/events/event-listener.md).

## Factory beans

A class that extends `FactoryBean<T>` gets `factoryObjectTypes`: the product type and its supertypes.

```dart
@Component()
class ProductFactory extends FactoryBean<Product> {
  @override
  Product getObject() => Product();
}

// Generated (part):
factoryObjectTypes: const [Product],
```

A lookup by these types, or by the bean's name, returns the product. `&productFactory` returns the factory itself. The product type must be a class type. See [FactoryBean](../spring-core-dart/beans/factory-bean.md).

## `@Bean` methods

A `@Bean` method gives a definition with `factoryMethodName`, and `factoryBeanName` for an instance method. Its `create` calls the method:

```dart
// An instance method of a @Component class, or of
// @Configuration(proxyBeanMethods: false): called on the owner bean.
create: (r) => r.dependency<AppConfig>(qualifier: r'appConfig').pool(),

// A static method: called on its class, no owner bean needed.
create: (r) => AppConfig.pool(),

// A full-mode @Configuration class: through its generated subclass (below).
create: (r) => (r.dependency<ShopConfig>(qualifier: r'shopConfig')
    as _$ShopConfigConfiguration)._$coverStore(r),
```

The returned object is treated like any bean: the `@Autowired` and `@Value` members, lifecycle methods and listeners of the returned type apply too. The class's conditions come first, then the method's. `annotations` holds the method's annotations, then those of the returned class.

The build fails for a private or generic `@Bean` method, an `async` one, one that returns an extension type, or one on a top-level function.

### The type is read from the body

The generator sees the method's body, so it registers the bean under the class the method really returns, not only the declared return type:

```dart
@Bean()
@ConditionalOnMissingBean(Clock)
Clock clock() => const SystemClock();
```

```dart
// Generated (simplified):
BeanDefinition<SystemClock>(
  name: r'clock',
  types: const [SystemClock, Clock],
  factoryBeanName: r'shopConfig',
  factoryMethodName: r'clock',
  conditions: [const ConditionalOnMissingBean(Clock)],
  dependencies: const [Dependency(ShopConfig, qualifier: r'shopConfig')],
  create: (r) => ((r.dependency<ShopConfig>(qualifier: r'shopConfig')
      as _$ShopConfigConfiguration)._$clock(r) as SystemClock),
  // ...
),
```

The types are the inferred class and its supertypes, then the declared type and its supertypes not yet listed. `create` casts the result to the inferred class. So lookups, conditions and AOP see a `SystemClock` before the bean exists. Spring only knows the declared type until it calls the method.

Several `return`s give their common supertype, and a `throw` is ignored. The generator keeps the declared type when the body returns a nullable type, a type generated code cannot name (private, internal to the SDK, or with type parameters), or when it cannot read the body.

A `@Bean` method may also return `T?` (a `null` result is stored as a `NullBean`), a function type or a record type.

## Full-mode `@Configuration`: a generated subclass

In Spring, a `@Configuration` class is subclassed with CGLIB, so that one `@Bean` method calling another gets the container's singleton, not a new object. The generator does the same with a generated Dart subclass, for a `@Configuration` class (`proxyBeanMethods: true`, the default) with at least one instance `@Bean` method.

```dart
@Configuration()
class ShopConfig {
  @Bean()
  @ConditionalOnMissingBean(Clock)
  Clock clock() => const SystemClock();

  // clock() is an inter-bean call: it returns the container's clock bean.
  @Bean()
  @Scope(ScopeType.prototype)
  ReceiptBuilder receiptBuilder(ShopProperties shop) =>
      ReceiptBuilder(shop.name, clock().now());
}
```

```dart
// Generated (simplified):
/// `ShopConfig` whose `@Bean` methods return the beans of the container
/// (full-mode `@Configuration`).
class _$ShopConfigConfiguration extends ShopConfig {
  _$ShopConfigConfiguration(this._$beanFactory);

  final BeanFactory _$beanFactory;

  final _$arguments = <String, List<Object?>>{};

  // Your code calls this: it returns the bean of the container.
  @override
  Clock clock() => (this._$beanFactory.getBeanByName(r'clock') as Clock);

  // The container calls this to create the bean: the original body.
  Clock _$clock(DependencyResolver r) => super.clock();

  @override
  ReceiptBuilder receiptBuilder(ShopProperties shop) {
    final _$args = <Object?>[shop];
    this._$arguments[r'receiptBuilder'] = _$args;
    try {
      return (this._$beanFactory.getBeanByName(r'receiptBuilder')
          as ReceiptBuilder);
    } finally {
      this._$arguments.remove(r'receiptBuilder');
    }
  }

  ReceiptBuilder _$receiptBuilder(DependencyResolver r) {
    final _$args = this._$arguments.remove(r'receiptBuilder');
    if (_$args != null) {
      return super.receiptBuilder((_$args[0] as ShopProperties));
    }
    return super.receiptBuilder(r.dependency<ShopProperties>(name: r'shop'));
  }
}

// The definition of the class creates the subclass:
BeanDefinition<ShopConfig>(
  name: r'shopConfig',
  create: (r) => _$ShopConfigConfiguration(r),
  annotations: const [Configuration()],
),
```

How it works:

1. The class's definition creates `_$ShopConfigConfiguration`, passing the container's `BeanFactory`, then the class's own constructor arguments.
2. Each instance `@Bean` method is overridden to return `getBeanByName('<bean name>')` (`'&<name>'` for a method that returns a `FactoryBean`). A call from one `@Bean` method to another goes through the container.
3. `_$<method>(r)` keeps the original body, and each `@Bean` definition's `create` calls it.
4. When your code passes arguments to a `@Bean` method and that call creates the bean, the arguments are used to create it, as Spring's `BeanMethodInterceptor` does. An existing singleton is returned as it is; a prototype is created with the arguments. Otherwise the parameters are resolved from the container.

Static `@Bean` methods are not intercepted, as in Spring. The build fails when the subclass cannot be written: a `sealed`, `final` or `interface` class, a class that cannot be extended outside its library, a factory or private constructor, or a `@Bean` parameter whose default value is not a constant. The error offers `@Configuration(proxyBeanMethods: false)`, which calls the methods as written ("lite" mode, also used for `@Component` classes with `@Bean` methods). See [@Configuration](../spring-core-dart/beans/configuration.md).

## `@Lookup` methods: a generated subclass

A `@Lookup` method returns a bean from the container on each call, so a singleton can get a new prototype every time. The generator writes a subclass that overrides each lookup method:

```dart
@Component()
abstract class OrderMailer {
  OrderMailer(
    @Value('resources:templates/order-confirmation.txt') this.template,
    this.messages,
    this.mail,
    this.shop,
  );
  // ...

  /// A new ReceiptBuilder (a prototype bean) per call.
  @Lookup()
  ReceiptBuilder newReceipt();
}
```

```dart
// Generated (simplified):
/// `OrderMailer` whose `@Lookup` methods return beans of the container.
class _$OrderMailerLookup extends OrderMailer {
  _$OrderMailerLookup(
    this._$beanFactory,
    super.p0,
    super.p1,
    super.p2,
    super.p3,
  );

  final BeanFactory _$beanFactory;

  @override
  ReceiptBuilder newReceipt() =>
      this._$beanFactory.getBean<ReceiptBuilder>();
}

BeanDefinition<OrderMailer>(
  name: r'orderMailer',
  dependencies: const [
    Dependency.value(r'resources:templates/order-confirmation.txt'),
    Dependency(MessageSource, name: r'messages'),
    Dependency(MailSender, name: r'mail'),
    Dependency(ShopProperties, name: r'shop'),
  ],
  create: (r) => _$OrderMailerLookup(
    r,
    r.value<Resource>(r'resources:templates/order-confirmation.txt'),
    r.dependency<MessageSource>(name: r'messages'),
    r.dependency<MailSender>(name: r'mail'),
    r.dependency<ShopProperties>(name: r'shop'),
  ),
  // ...
),
```

- The override calls `getBean<T>()`, `findBean<T>()` for a nullable return type, or `getBeanByName('name')` for `@Lookup('name')`.
- A class with `@Lookup` methods may be abstract; any other abstract class is not a bean and fails the build.
- A `@Lookup` method must be public, not static, not generic. `@Lookup` on a getter, setter or field fails the build: declare a method.
- When the bean also gets a subclass AOP proxy, the proxy extends the lookup class.

See [@Lookup](../spring-core-dart/beans/lookup.md).

## Annotations

`annotations` holds the annotations of the bean class, written again as constants, so `findAnnotationOnBean` and `getBeansWithAnnotation` work without reflection. For a `@Bean` method it holds the method's annotations, then those of the returned class. An annotation is kept when it is public, not from the SDK, and can be written as a constant (no private values). Others are left out silently.

## `aopProxy` and `aspect`

`aopProxy` tells the container how to wrap the bean when an aspect applies to it:

- `AopProxyFactory(...)`: a generated proxy class that implements the bean's types and forwards to the bean;
- `AopProxyFactory.subclass(...)`: a generated subclass, for a class that can only be extended; the bean itself is created through it;
- `const AopProxyFactory.pruned(...)`: no proxy class, because no advice of the application can match the bean;
- `const AopProxyFactory.deferred(...)`: a starter's bean, whose proxy class the application's build writes;
- `AopProxyFactory.unavailable(reason: ...)`: no proxy can be written (private members, a `final` class without an interface); the reason says what to change.

Configuration classes, aspects and infrastructure beans get no `aopProxy`. An `@Aspect` class gets `aspect:`, its advice and pointcuts, parsed at build time. See [AOP proxies: pruning and deferring](optimizations/aop-proxies.md) and [Proxies](../spring-core-dart/aop/proxies.md).

## Annotated methods

A method with an annotation marked `@BeanMethodAnnotation()`, such as `@Scheduled`, is listed in `annotatedMethods` as an `IntrospectedMethod`: its name, its parameters, its annotations and a function that calls it. A starter finds these methods at run time and calls them (the scheduler starts every `@Scheduled` method). See [Bean method annotations](../spring-core-dart/beans/bean-method-annotation.md).

## In Spring (Java)

```java
// ClassPathBeanDefinitionScanner reads class files when the context
// starts and registers a ScannedGenericBeanDefinition per component;
// ConfigurationClassBeanDefinitionReader adds one per @Bean method.
// Reflection then creates and injects the instances.
@Service
@Lazy
class Greeter {
  Greeter(Clock clock) {}
  @PostConstruct void init() {}
}
```

Differences that matter:

- The definitions are written at build time. Run `build_runner` after you change annotations.
- `types` lists every supertype, because Dart cannot test subtypes of a `Type` at run time.
- A `@Bean` definition is registered under the class its body returns, not only the declared return type.
- An `@EventListener` condition is a function, not a SpEL string.

## See also

- [@ComponentScan modules](component-scan.md)
- [The application: @SpringBootApplication](spring-boot-application.md)
- [Build-time checks](checks.md)
- [Only what runs: introspection](optimizations/introspection.md)
- [Beans in spring_core_dart](../spring-core-dart/beans/index.md)
