3.18 Importing Beans from Libraries

You can use the @Import annotation to import beans from external, already compiled libraries that use JSR-330 annotations.

Bean import is currently only supported in the Java language as other languages have limitations on classpath scanning during source code processing.

For example, to import the JSR-330 TCK into an application, add a dependency on the TCK:

  1. implementation("io.micronaut:jakarta.inject")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>jakarta.inject</artifactId>
  4. </dependency>

Then define the @Import annotation on your Application class:

  1. package example;
  2. import io.micronaut.context.annotation.Import;
  3. @Import( (1)
  4. packages = { (2)
  5. "org.atinject.tck.auto",
  6. "org.atinject.tck.auto.accessories"},
  7. annotated = "*") (3)
  8. public class Application {
  9. }
1The @Import is defined
2The packages to import are defined. Note that Micronaut will not recurse through sub-packages so sub-packages need to be listed explicitly
3By default Micronaut will only import classes that feature a scope or a qualifier. By using * you can make every type a bean.
In general @Import should be used in applications rather than libraries since if two libraries import the same beans the result will likely be a NonUniqueBeanException