I have a basic Spring Boot application annotated like this:
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
I have the following entries in my application.properties
file:
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/db
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
From my understanding Spring Boot should be able to automatically autowire a DataSource Bean from these properties.
However if I try:
@Autowired
DataSource dataSource;
anywhere in my application (f.i. in @Configuration files), I get the following error in IntelliJ:
"Could not autowire. No beans of 'DataSource' type found."
Is there something obvious that I'm missing for this to work?
I have a single DataSource.
To configure your own DataSource , define a @Bean of that type in your configuration. Spring Boot reuses your DataSource anywhere one is required, including database initialization. If you need to externalize some settings, you can bind your DataSource to the environment (see “Section 25.8.
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. This is called Spring bean autowiring.
The bean actually does get initialized correctly. This is possibly just an IntelliJ tooltip bug.
Adding @SuppressWarnings to hide the message will work without further issues.
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