
# @BeanMethodAnnotation

`@BeanMethodAnnotation()` marks an annotation class whose methods the runtime can find on beans.

## Why

Libraries that act on annotated bean methods need to find and call them: a scheduler running `@Scheduled` methods, a message consumer, a command dispatcher. Java finds them by reflection. Dart in Flutter and AOT has no reflection.

Put `@BeanMethodAnnotation()` on such an annotation class. For every bean method carrying it, the generator writes a `BeanMethod` into `BeanDefinition.annotatedMethods`. A `BeanMethod` holds the method's name, its annotations and a closure that calls it.

Application code rarely needs this. Library and starter authors do. This is how the scheduling starter finds `@Scheduled` methods.

## Example

```dart
import 'dart:async';

import 'package:spring_core_dart/spring_core_dart.dart';

// The library's annotation.
@BeanMethodAnnotation()
class Poll {
  const Poll(this.every);
  final Duration every;
}

// The application's bean.
@Component()
class Inbox {
  @Poll(Duration(seconds: 30))
  void check() {
    // fetch new messages
  }
}

// The library: after startup, start a timer for every @Poll method.
void startPolling(ConfigurableApplicationContext context) {
  final factory = context.beanFactory;
  for (final name in factory.beanDefinitionNames) {
    for (final method in factory.getBeanDefinition(name).annotatedMethods) {
      final poll = method.annotations.whereType<Poll>().firstOrNull;
      if (poll != null) {
        final bean = context.getBeanByName(name);
        Timer.periodic(poll.every, (_) => method.invoke(bean, const []));
      }
    }
  }
}
```

A library would usually run this from a `SmartLifecycle` bean or a `BeanPostProcessor`, so that it starts and stops with the context.

## Parameters

None.

## In Spring (Java)

Spring has no equivalent annotation. It finds such methods by reflection:

```java
Map<Method, Poll> methods = MethodIntrospector.selectMethods(
    beanClass,
    (MethodIntrospector.MetadataLookup<Poll>) method ->
        AnnotatedElementUtils.findMergedAnnotation(method, Poll.class));
```

## See also

- [BeanPostProcessor](bean-post-processor.md)
- [Lifecycle and SmartLifecycle](lifecycle.md)
- [ConfigurableListableBeanFactory](configurable-listable-bean-factory.md)
- [Events](../events/index.md)
