Java / Micronaut Interview questions
When should you use @Factory in Micronaut?
Use @Factory when you need to produce a bean that Micronaut can't construct directly, typically because it comes from a third-party class you don't control, needs custom construction logic, or requires multiple related beans built from shared setup.
@Factory public class DataSourceFactory { @Singleton public DataSource dataSource(DataSourceConfig config) { HikariConfig hc = new HikariConfig(); hc.setJdbcUrl(config.getUrl()); return new HikariDataSource(hc); } }
Each method inside a @Factory class annotated with a scope like @Singleton becomes its own bean, built by calling that method rather than a constructor. This is the standard pattern for wiring libraries such as connection pools, HTTP client builders, or SDK clients that expose static or builder-based construction instead of a plain injectable constructor.
More Related questions...