@ComponentScan modules

A top-level variable with @ComponentScan() marks a scan root. The generator collects every bean of that file's directory and below, and writes them into one BeanModule, returned by a getter named after the variable with a $ in front.

// lib/src/beans.dart
import 'package:spring_core_dart/spring_core_dart.dart';
import 'package:my_app/spring_gen/src/beans.spring.dart'; // written by the generator

@ComponentScan()
final BeanModule appBeans = $appBeans;

The generated file is lib/spring_gen/src/beans.spring.dart, and it declares BeanModule get $appBeans.

Why

In Spring, @ComponentScan("com.example.app") tells the container which packages to search when it starts. Dart has no packages in that sense and no way to search classes at run time. So the generator searches at build time, and the search area is a directory: the directory of the annotated file.

The variable makes the module a normal Dart value. You pass it to a context, import it from another module, or let a @SpringBootApplication find it. The getter it reads from is generated, so after every build the variable holds the beans of the current code.

Most applications do not need @ComponentScan at all: @SpringBootApplication() on main scans the whole package (see @SpringBootApplication). Use @ComponentScan for:

The generated module

For a scan root in lib/src/ with two bean classes:

// lib/src/beans.dart
@ComponentScan()
final BeanModule appBeans = $appBeans;

// lib/src/info_controller.dart
@RestController()
@RequestMapping('/api')
class InfoController {
  InfoController(@Value(r'${spring.application.name}') this.name);

  final String name;

  @GetMapping('/info')
  Map<String, dynamic> info() => {'name': name};
}

The generator writes (simplified from example/static_site/server of the repository: import prefixes such as _i1. dropped, the method metadata and the long resource texts shortened):

// lib/spring_gen/src/beans.spring.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from @ComponentScan.

/// Beans found by `@ComponentScan` in `lib/src`.
BeanModule get $appBeans => BeanModule(
  r'appBeans',
  [
    BeanDefinition<InfoController>(
      name: r'infoController',
      source: r'package:my_app/src/info_controller.dart#InfoController',
      dependencies: const [Dependency.value(r'${spring.application.name}')],
      create: (r) => InfoController(r.value<String>(r'${spring.application.name}')),
      annotatedMethods: [
        IntrospectedMethod<InfoController>(r'info', /* ... */ annotations: [GetMapping(r'/info')]),
      ],
      annotations: const [RestController(), RequestMapping(r'/api')],
      aopProxy: const AopProxyFactory.pruned(/* ... */),
    ),
  ],
  resources: const {
    r'application.yml': EmbeddedResource.text('spring:\n  application:\n    name: static-site\n...'),
  },
);

The parts of the file:

Part What it is
The getter name $ + the variable's name: appBeans → $appBeans.
The first argument The module's name, the variable's name: r'appBeans'. It appears in logs and errors.
The list One BeanDefinition per bean, in the order of the files (sorted by path) and of the declarations in each file. See Bean definitions.
imports: The modules of nested scan roots (see below).
resources: The files of the package's lib/resources/ (see Embedded resources).
Other arguments Only when needed: propertySources: (@PropertySource), registrars: (@Import of a registrar), introspections:, configurers: (@Configurable), aopProxies:, typeTests: and typeDepths: (for annotations matched by type).

After the getter come the generated @Log extensions and, for Flutter, the BuildContext extension. Before it come the generated classes: AOP proxies, @Configuration and @Lookup subclasses, data repositories.

The getter is a getter, not a variable, so that a hot reload, which replaces its body, makes the next call return the beans of the new code.

Using the module

Pass the variable to a context:

import 'package:spring_core_dart/spring_core_dart.dart';
import 'package:my_app/src/beans.dart';

void main() {
  final context = ApplicationContext.run([appBeans]);
  final controller = context.getBean<InfoController>();
}

In an application with @SpringBootApplication() on main, a scan root under lib/ is found by the application's scan and added to its imports: (see @SpringBootApplication). A starter lists its modules in lib/spring_auto_configuration.dart instead (see Auto-configurations).

Which files are scanned

The scan root is the directory of the annotated file. The generator takes every .dart file below it, at any depth:

lib/src/
  beans.dart              @ComponentScan() appBeans    ← scan root
  greeter.dart            scanned by appBeans
  shop/
    basket.dart           scanned by appBeans
    payment/
      card.dart           scanned by appBeans

Rules:

In each library, the generator looks at:

An abstract class is skipped, unless it has @Lookup methods (the generator then writes a concrete subclass, see Bean definitions).

Nested scans

A file below the scan root that declares its own @ComponentScan owns its directory. Its files are left out of the outer module, and its module is imported instead:

lib/src/
  beans.dart                @ComponentScan() appBeans
  greeter.dart              → appBeans
  shop/
    shop_beans.dart         @ComponentScan() shopBeans
    basket.dart             → shopBeans
    payment/
      payment_beans.dart    @ComponentScan() paymentBeans
      card.dart             → paymentBeans
// lib/spring_gen/src/beans.spring.dart (simplified)
BeanModule get $appBeans => BeanModule(
  r'appBeans',
  [
    BeanDefinition<Greeter>(/* ... */),
  ],
  imports: [shopBeans],
);

// lib/spring_gen/src/shop/shop_beans.spring.dart (simplified)
BeanModule get $shopBeans => BeanModule(
  r'shopBeans',
  [
    BeanDefinition<Basket>(/* ... */),
  ],
  imports: [paymentBeans],
);

A directory has one scan root. Two @ComponentScan files in the same directory fail the build:

Two @ComponentScan roots in lib/src/: lib/src/beans.dart and lib/src/more_beans.dart.
A directory has one scan root; remove one, or move it into a subdirectory (which the
other then imports).

Scan options

@ComponentScan takes Spring's scan options. They are read from the annotation as constants and evaluated by the generator, so they never reach the running program: a class a filter rejects simply has no BeanDefinition.

Option Type Default Effect
includeFilters List<Filter> [] Classes matching one of these become beans even without @Component.
excludeFilters List<Filter> [] Classes matching one of these never become beans, whatever else matches. Their @Bean methods are skipped with them.
useDefaultFilters bool true Whether @Component (and annotations extending it) marks a bean. With false, only includeFilters make beans.
lazyInit bool false Every bean of the module (components and their @Bean methods) is created on first use, unless it says @Lazy(false).

A class is a bean of the module when:

  1. no exclude filter matches it (excludes always win);
  2. and either useDefaultFilters is true and the class has @Component or a stereotype,
  3. or the class is not abstract and an include filter matches it.

A Filter has three kinds:

type Uses Matches a class that
FilterType.annotation (default) classes has an annotation of one of the classes, or of a subclass of one (Dart's form of Spring's meta-annotations)
FilterType.assignableType classes is, extends, implements or mixes in one of the classes
FilterType.regex pattern has a class name in which one of the regular expressions matches. The expression is tested against the simple class name (BookRepository), and matches anywhere unless you anchor it with ^ and $.

Examples

Plugins marked with an annotation of your own, without @Component:

class Plugin {
  const Plugin();
}

@ComponentScan(includeFilters: [Filter(classes: [Plugin])])
final BeanModule plugins = $plugins;

// lib/src/plugins/pdf_export.dart: a bean of `plugins`
@Plugin()
class PdfExport {}

Every implementation of an interface, and nothing else:

@ComponentScan(
  useDefaultFilters: false,
  includeFilters: [
    Filter(type: FilterType.assignableType, classes: [Handler]),
  ],
)
final BeanModule handlers = $handlers;

Everything but the classes whose name ends in Stub, all lazy:

@ComponentScan(
  excludeFilters: [
    Filter(type: FilterType.regex, pattern: [r'Stub$']),
  ],
  lazyInit: true,
)
final BeanModule appBeans = $appBeans;

With lazyInit: true, a bean can still start eagerly:

@Service()
@Lazy(false)
class Warmup {}

Errors

Every error points at the declaration that causes it.

Mistake Message
@ComponentScan on a class, function, field, method, getter, ... @ComponentScan on class AppConfig of package:my_app/src/config.dart: put it on a top-level variable holding the generated module, e.g. @ComponentScan() final BeanModule appBeans = $appBeans;
Two @ComponentScan variables in one file Only one @ComponentScan is allowed per file.
A private variable, or one whose name starts with $ @ComponentScan variable must be public and must not start with $.
Two scan roots in one directory Two @ComponentScan roots in lib/src/: ... (above)
A filter without what its type uses, with the wrong argument, or with an invalid regular expression see below
Two unconditional beans with one name or alias Bean name 'clock' is used by both clock and SystemClock.

A filter error names the option and the position of the filter in its list:

@ComponentScan includeFilters[0]: a FilterType.regex filter needs `pattern`.
@ComponentScan excludeFilters[0]: a FilterType.annotation filter uses `classes`, not `pattern`.
@ComponentScan includeFilters[1]: invalid pattern '[': ...
@ComponentScan includeFilters[0]: `classes` must list classes.

Beans with conditions (@Profile('dev') and @Profile('prod'), both named dataSource) may share a name: the container registers the one whose condition matches, and reports a real clash when the context starts.

The other build errors of the scanned declarations are on Build-time checks.

In Spring (Java)

@Configuration
@ComponentScan(
    basePackages = "com.example.shop",
    includeFilters = @Filter(type = FilterType.ANNOTATION, classes = Plugin.class),
    excludeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub"),
    lazyInit = true)
class ShopConfig {}

Differences:

See also