DEV Community

eidher
eidher

Posted on • Edited on

How Spring implements Singleton Beans

In the next example, the dataSource method is a bean that is called twice. However, we know that a bean is a singleton by default in Spring (see the link below):


@Configuration
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        return new JdbcDataSource();
    }

    @Bean
    public DevRepository devRepository() {
        JdbcDevRepository repository = new JdbcDevRepository(dataSource);
        repository.setDataSource(dataSource());
        return repository;
    }

    @Bean
    public ProdRepository prodRepository() {
        JdbcProdRepository repository = new JdbcProdRepository();
        repository.setDataSource(dataSource());
        return repository;
    }
}
Enter fullscreen mode Exit fullscreen mode

At startup time, a subclass is created using cglib (Code Generation Library). It only calls super in the first invocation of the bean, then one instance is cached by the application context and the child class is the entry point.

@Configuration
public class AppConfig$$EnhancerByCGLIB$ extends AppConfig{
...
}
Enter fullscreen mode Exit fullscreen mode

However, cglib does not support classes with constructors (autowired constructors are possible since Spring 4.3. See Spring Injection Types), so Spring now uses objenesis to overcome this.

Top comments (0)