Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - Autowiring a DataSource Bean

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.

like image 968
Bragolgirith Avatar asked May 31 '16 16:05

Bragolgirith


People also ask

How do you configure a DataSource in Spring?

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.

How do I create an Autowired Bean?

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.


1 Answers

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.

like image 58
Bragolgirith Avatar answered Sep 28 '22 04:09

Bragolgirith