Autowire a bean within Spring’s Java configuration

If you need a reference to the DataSource bean within the same @Configuration file, just invoke the bean method.

@Bean
public OtherBean someOtherBean() {
    return new OtherBean(dataSource());
}

or have it autowired into the @Bean method

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

The lifecycle of a @Configuration class sometimes prevents autowiring like you are suggesting.

You can read about Java-based container configuration, here. This section goes into detail about how @Configuration classes are proxied and cache the beans that the define, so that you can call @Bean annotated methods but only every get back one object (assuming the bean is singleton scoped).

Leave a Comment