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

2

8

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?

Waylin answered 23/9, 2016 at 17:51 Comment(3)
You don't need to define the dataSource bean, it will be created by Spring but you need the properties defined and the driver in the classpath.Bodoni
Ok cool, so basically the config I listed first? Thanks!Waylin
make sure you have "org.springframework.boot spring-boot-starter-data-jpa" added to your project to make the autoconfiguration workRammish
P
14

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.

Palmira answered 23/9, 2016 at 17:56 Comment(2)
Ok, so I can just ignore Intellij telling me it can't find a bean of type 'Datasource'?Waylin
Read the docs, and do a test run of your app.Palmira
A
1

Try this . If there are multiple @Configuration in springboot , You can import the the other config(DataSourceConfig) into your main AppConfig. And then Using @PropertySource pull in the db url,username,password etc

https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch04s03.html

@Configuration
    @Import(DataSourceConfig.class)
    @PropertySource("classpath:application.properties")
    public class SpringbatchConfig {
        @Autowired
        DataSourceConfig dataSourceConfig;

        @Bean
        public void myService myService() {
            return new myServiceImpl(dataSourceConfig.dataSource());
        }
    }
Adventurous answered 16/1, 2023 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.