Video in progress

Strong Junior 🌱 Spring

What is the difference between @Bean methods inside @Configuration and inside @Component?

A @Configuration class is wrapped in a CGLIB proxy, so when one @Bean method calls another, you get the singleton from the container. In a @Component (lite mode) that's an ordinary Java call, which creates a new object every time.

📖 Answer

@Configuration
class AppConfig {
    @Bean DataSource dataSource() { return new HikariDataSource(...); }

    @Bean JdbcTemplate jdbc() { return new JdbcTemplate(dataSource()); }
    @Bean TransactionManager tx() { return new DataSourceTransactionManager(dataSource()); }
}

With @Configuration, jdbc() and tx() both get the same DataSource: the proxy intercepts the dataSource() call and returns the ready bean from the container.

Now write @Component instead of @Configuration. The code looks the same, but dataSource() is now a plain method: called twice, it creates two connection pools. One isn't in the container, nobody closes it, and the transaction manager and the JdbcTemplate work with different pools. An error like this is very hard to find.

@Configuration(proxyBeanMethods = false) also works like lite mode. Spring Boot's own auto-configurations are written exactly this way: not creating a proxy makes startup faster.

The safe approach is to get the dependency through a parameter, not a method call:

@Bean JdbcTemplate jdbc(DataSource ds) { return new JdbcTemplate(ds); }

Then the result is correct in either mode.