Spring Boot - Autowiring a DataSource Bean

别来无恙 提交于 2019-12-23 08:06:07

问题


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.


回答1:


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.




回答2:


Intelij apparently even in the 2016.2 still does not support the @SpringBootApplication annotation. You either have to remove the @SpringBootApplication annotation and replace it with the @Configuration, @EnableAutoConfiguration and @ComponentScan annotations or just ignore the errors.



来源:https://stackoverflow.com/questions/37550911/spring-boot-autowiring-a-datasource-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!