Search code examples
javaspring

Autowire a bean within Spring's Java configuration


Is it possible to use Spring's @Autowired annotation within a Spring configuration written in Java?

For example:

@Configuration
public class SpringConfiguration{

   @Autowired 
   DataSource datasource;

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

   // ...

}

Obviously a DataSource interface cannot be directly instantiated but I directly instantiated it here for simplification. Currently, when I try the above, the datasource object remains null and is not autowired by Spring.

I got @Autowired to work successfully with a Hibernate SessionFactory object by returning a FactoryBean<SessionFactory>.

So my question specifically: is there a way to do that with respect to a DataSource? Or more generally, what is the method to autowire a bean within a Spring Java Configuration?

I should note I am using Spring version 3.2.


Solution

  • 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).