Annotation Type Factory


@Target(TYPE) @Retention(RUNTIME) public @interface Factory
A singleton bean that has methods marked with the @Bean annotation.

Factory beans allow us to build beans using logic in methods. These methods for example often use environment variables and system properties into account when building the bean.

Relative to jakarta.inject.Provider Factory and Bean provide a more flexible approach that allows dependencies on the method (as method parameters) as well as multiple methods on the single factory bean. The expectation is that we tend to use Factory and Bean rather than Provider.



 @Factory
 class Configuration {

   private final StartConfig startConfig;

   @Inject
   Configuration(StartConfig startConfig) {
     this.startConfig = startConfig;
   }

   @Bean
   Foo buildFoo() {
     ...
     return new Foo(...);
   }

   @Bean
   Bar buildBar(Foo foo, Bazz bazz) {
     ...
     return new Bar(...);
   }
 }