Use it like this:
@Bean
@Lazy
public Map<String, String> someDatabaseTableValues() {
//the following JdbcTemplate instance will already be configured by Spring
JdbcTemplate template = jdbcTemplate();
...
}
Some explanation: Spring needs CGLIB for @Configuration
class processing. It effectively makes a CGLIB proxy out of your configuration classes. When you invoke a @Bean
method on your configuration class, it will be handled by the CGLIB proxy. The proxy interceptor will check if an already configured instance of the bean is readily available (for singleton beans) and return that cached instance. If there's no cached instance, it will invoke your @Bean
factory method and apply any configuration and bean postprocessing your application context is set up to do. When it returns it will cache the bean instance if needed (again, in case of singleton beans) and return the configured bean instance to you.
You can also use method-injection with @Autowired
:
@Autowired
@Bean
@Lazy
public Map<String, String> someDatabaseTableValues(JdbcTemplate template) {
...
}
You can use @Qualifier()
annotation in front of your autowired method parameters do distinguish between multiple instances of the same bean type.
Note that you could also use JSR-250's @Resource
or JSR-330's @Inject
annotations instead of @Autowired
, as those are supported as well by Spring.
someDatabaseTableValues(JdbcTemplate template)
.@DependsOn("jdbcTemplate")
instead of@Lazy
and invokeJdbcTemplate jdbcTemplate = jdbcTemplate(); ...
inside yoursomeDatabaseTableValues()
method. The first annotation gurantees that the jdbcTemplate bean is initialized beforesomeDatabaseTableValues()
is being initialized. Skipping@DependsOn
may result in a circular reference exception. In addition to that, it's always safe to name your beans, i.e.@Bean(name = "jdbcTemplate") ...