@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:
- a library package that ships beans, such as a starter or a shared module of a workspace;
- an application built with
ApplicationContextalone, withoutspring_boot_dart; - splitting a large application into modules (one per feature directory), with their own scan options;
- a test application under
test/.
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:
- The files are sorted by path, so the definitions come out in the same order on every machine.
- Generated
.spring.dartfiles are never scanned. - Part files are read through their library.
- Files above or beside the scan root are not scanned, even when a scanned file imports them. A bean in
lib/util.dartis not in a module rooted atlib/src/.
In each library, the generator looks at:
- classes with
@Componentor an annotation that extends it (@Service,@Repository,@Controller,@RestController,@Configuration, ...), and classes an include filter matches; - the
@Beanmethods of those classes; - what starters define as beans without
@Component: interfaces that extendDataRepository(spring_boot_starter_data),@InterfaceProxyinterfaces such as Feign clients; - classes that need generated code without being beans:
@Configurable,@Introspected,@Log, Flutter widgets with beans.
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],
);
- Only the outermost nested scans are imported.
appBeansimportsshopBeans, andshopBeansimportspaymentBeans;appBeansdoes not importpaymentBeansdirectly. - What is imported is your variable (
shopBeans), not the generated getter. A top-levelfinalvariable is created once, so the same module object is used wherever it is imported, and the context loads it once. - Imported modules are loaded before the module that imports them.
- Each bean is in exactly one module. Using
appBeansandshopBeanstogether in one context does not registerBaskettwice. Spring's scanner likewise skips candidates an overlapping scan already registered. - Each module keeps its own scan options; the options of
appBeansdo not apply toshopBeans.
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:
- no exclude filter matches it (excludes always win);
- and either
useDefaultFiltersistrueand the class has@Componentor a stereotype, - 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:
- The search area is the directory of the annotated file and below. There is no
basePackagesorbasePackageClasses. @ComponentScangoes on a top-level variable that holds the generated module, not on a@Configurationclass.- The filters are evaluated at build time.
FilterType.ASPECTJandFilterType.CUSTOMdo not exist, since they would need code to run during the build. - A regex filter is tested against the simple class name and matches anywhere in it; Spring matches the whole fully qualified class name.
- Nested scan roots are imported, so each bean belongs to one module.
See also
- @ComponentScan: the annotation, from the runtime's side.
- BeanModule
- @Lazy
- Bean definitions