Annotation Type Factory


@Target(TYPE) @Retention(SOURCE) 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 javax.inject.Provider, Factory and Bean provides a more flexible approach that allows dependencies on the method (as method parameters) as well as multiple methods on the single factory bean.



 @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(...);
   }
 }