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.
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.
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.
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.
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With