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

```dart
// 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](spring-boot-application.md)). Use `@ComponentScan` for:

- a library package that ships beans, such as a starter or a shared module of a workspace;
- an application built with `ApplicationContext` alone, without `spring_boot_dart`;
- splitting a large application into modules (one per feature directory), with their own [scan options](#scan-options);
- a test application under `test/`.

## The generated module

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

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

```dart
// 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](bean-definitions.md). |
| `imports:` | The modules of nested scan roots (see [below](#nested-scans)). |
| `resources:` | The files of the package's `lib/resources/` (see [Embedded resources](resources.md)). |
| 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:

```dart
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](spring-boot-application.md#nested-componentscan-roots)). A starter lists its modules in `lib/spring_auto_configuration.dart` instead (see [Auto-configurations](auto-configurations.md)).

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

```text
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.dart` files 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.dart` is not in a module rooted at `lib/src/`.

In each library, the generator looks at:

- classes with `@Component` or an annotation that extends it (`@Service`, `@Repository`, `@Controller`, `@RestController`, `@Configuration`, ...), and classes an [include filter](#scan-options) matches;
- the `@Bean` methods of those classes;
- what starters define as beans without `@Component`: interfaces that extend `DataRepository` (`spring_boot_starter_data`), `@InterfaceProxy` interfaces 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](bean-definitions.md)).

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

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

```dart
// 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. `appBeans` imports `shopBeans`, and `shopBeans` imports `paymentBeans`; `appBeans` does not import `paymentBeans` directly.
- What is imported is your variable (`shopBeans`), not the generated getter. A top-level `final` variable 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 `appBeans` and `shopBeans` together in one context does not register `Basket` twice. Spring's scanner likewise skips candidates an overlapping scan already registered.
- Each module keeps its own [scan options](#scan-options); the options of `appBeans` do not apply to `shopBeans`.

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

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

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

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

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

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

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

```text
@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](checks.md).

## In Spring (Java)

```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 `basePackages` or `basePackageClasses`.
- `@ComponentScan` goes on a top-level variable that holds the generated module, not on a `@Configuration` class.
- The filters are evaluated at build time. `FilterType.ASPECTJ` and `FilterType.CUSTOM` do 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](../spring-core-dart/beans/component-scan.md): the annotation, from the runtime's side.
- [BeanModule](../spring-core-dart/beans/bean-module.md)
- [@Lazy](../spring-core-dart/beans/lazy.md)
- [Bean definitions](bean-definitions.md)
