Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire a bean within Spring's Java configuration

Tags:

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.

like image 364
Avanst Avatar asked Feb 26 '15 16:02

Avanst


People also ask

How do you Autowire beans from configuration?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.

Can we Autowire a bean in configuration class?

In addition to being able to reference any particular bean definition as seen above, one @Configuration class may reference the instance of any other @Configuration class using @Autowired . This works because the @Configuration classes themselves are instantiated and managed as individual Spring beans.

Can we Autowire configuration class in Spring boot?

Enabling @Autowired Annotations The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans.

Can we use @bean without @configuration?

@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.


1 Answers

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.

like image 120
Sotirios Delimanolis Avatar answered Nov 14 '22 05:11

Sotirios Delimanolis