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

// 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;
}
// 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.

@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.

@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

@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());
}
// 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',
  // ...
),

Order, description, depends-on and qualifiers

@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)],
  // ...
),

Conditions

Three kinds of annotations become conditions:

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 @Imports and its @PropertySources, so they are decided once, all or nothing, as Spring decides per class.

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

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

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

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.

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:

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.

@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) { ... }
}
// 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:

A field declared by a primary constructor parameter is injected through the constructor, not as a field. See @Autowired.

Lifecycle callbacks

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();
}
// Generated (simplified):
postConstruct: (bean) {
  bean.postConstruct();
},
initMethod: (bean) {
  bean.customInit();
},
initMethodName: r'customInit',
preDestroy: (bean) {
  bean.preDestroy();
},
destroyMethod: (bean) {
  bean.customDestroy();
},
destroyMethodName: r'customDestroy',

When the context creates a bean it calls, in order: create, inject, the aware callbacks, postProcessBeforeInitialization, postConstruct, afterPropertiesSet, initMethod, postProcessAfterInitialization. On close: the DestructionAwareBeanPostProcessors, preDestroy, DisposableBean.destroy, destroyMethod. See Lifecycle.

Event listeners

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

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

@Component()
class VipDesk {
  @EventListener(condition: isVipOrder)
  @Order(2)
  void onVipOrder(OrderPlaced placed) { ... }
}
// 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.

Factory beans

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

@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.

@Bean methods

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

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

@Bean()
@ConditionalOnMissingBean(Clock)
Clock clock() => const SystemClock();
// 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 returns 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.

@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());
}
// 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.

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

@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();
}
// 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'),
  ),
  // ...
),

See @Lookup.

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:

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 and Proxies.

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.

In Spring (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:

See also