Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 925
fun_hat Avatar asked Sep 23 '16 17:09

fun_hat


People also ask

What is Springsource data boot?

Spring boot datasource configuration is nothing but the factory of connection which was used in a physical data source. Spring boot datasource uses the database credential to set up connections between the database server, it is alternative to the facility of Driver Manager.

How do I print datasource properties in Spring boot?

You can use dataSource. toString() to see its values. It's for debugging purpose, inject it somewhere and call toString() or breakpoint there and evaluate its values. Try injecting HikariDatasource with @Autowired .


1 Answers

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.

like image 65
Tassos Bassoukos Avatar answered Oct 01 '22 19:10

Tassos Bassoukos