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

fun_hat picture fun_hat · Sep 23, 2016 · Viewed 18.3k times · Source

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?

Answer

Tassos Bassoukos picture Tassos Bassoukos · Sep 23, 2016

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.