How do you autowire/inject your datasource in Spring-boot?

∥☆過路亽.° 提交于 2021-02-07 19:17:58

问题


I have been working with Spring boot for a bit now, and the datasource is always configured in your application.properties in every example I have seen, kind of like this:

# DataSource configuration
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/abcdef
spring.datasource.username=******
spring.datasource.password=******

However, lately I have been trying to integrate Spring Social, and the examples I have seen configure it in java in a config file like this:

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("db.driver"));
    dataSource.setUrl(env.getProperty("db.url"));
    dataSource.setUsername(env.getProperty("db.username"));
    dataSource.setPassword(env.getProperty("db.password"));
    return dataSource;
}

This allows for the datasource object to later be injected or autowired into the social config as seen here for example.

My question is, do I need to configure a datasource bean like this to be able to later inject the datasource, or will Spring-boot handle that for me?


回答1:


Not a Spring (or Boot) expert by any means, but Spring Boot will auto-provide a Bean of type DataSource if the properties are there and there's a requirement for it. To use it you just @Autowire it.



来源:https://stackoverflow.com/questions/39666777/how-do-you-autowire-inject-your-datasource-in-spring-boot

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