3.8 Conditional Beans

At times you may want a bean to load conditionally based on various potential factors including the classpath, the configuration, the presence of other beans etc.

The Requires annotation provides the ability to define one or many conditions on a bean.

Consider the following example:

Using @Requires

  1. @Singleton
  2. @Requires(beans = DataSource.class)
  3. @Requires(property = "datasource.url")
  4. public class JdbcBookService implements BookService {
  5. DataSource dataSource;
  6. public JdbcBookService(DataSource dataSource) {
  7. this.dataSource = dataSource;
  8. }

Using @Requires

  1. @Singleton
  2. @Requires(beans = DataSource.class)
  3. @Requires(property = "datasource.url")
  4. class JdbcBookService implements BookService {
  5. DataSource dataSource

Using @Requires

  1. @Singleton
  2. @Requirements(Requires(beans = [DataSource::class]), Requires(property = "datasource.url"))
  3. class JdbcBookService(internal var dataSource: DataSource) : BookService {

The above bean defines two requirements. The first indicates that a DataSource bean must be present for the bean to load. The second requirement ensures that the datasource.url property is set before loading the JdbcBookService bean.

Kotlin currently does not support repeatable annotations. Use the @Requirements annotation when multiple requires are needed. For example, @Requirements(Requires(…​), Requires(…​)). See https://youtrack.jetbrains.com/issue/KT-12794 to track this feature.

If you have multiple requirements that you find you may need to repeat on multiple beans then you can define a meta-annotation with the requirements:

Using a @Requires meta-annotation

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target({ElementType.PACKAGE, ElementType.TYPE})
  4. @Requires(beans = DataSource.class)
  5. @Requires(property = "datasource.url")
  6. public @interface RequiresJdbc {
  7. }

Using a @Requires meta-annotation

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target([ElementType.PACKAGE, ElementType.TYPE])
  4. @Requires(beans = DataSource.class)
  5. @Requires(property = "datasource.url")
  6. @interface RequiresJdbc {
  7. }

Using a @Requires meta-annotation

  1. @Documented
  2. @Retention(AnnotationRetention.RUNTIME)
  3. @Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
  4. @Requirements(Requires(beans = [DataSource::class]), Requires(property = "datasource.url"))
  5. annotation class RequiresJdbc

In the above example an annotation called RequiresJdbc is defined that can then be used on the JdbcBookService instead:

Using a meta-annotation

  1. @RequiresJdbc
  2. public class JdbcBookService implements BookService {
  3. ...
  4. }

If you have multiple beans that need to fulfill a given requirement before loading then you may want to consider a bean configuration group, as explained in the next section.