spring boot: how to configure datasource from application properties

Dan :

I want the below code values: DriverClassName, Url, Username, Password to be read from application.properties file, how to do that? I am using Spring Boot, Mysql, Hibernate and Spring Rest.

DatasourceConfig.java

    //This is working fine with inline value specified as below (DriverClassName, Url,Username,Password
    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(basePackages = "com.nouhoun.springboot.jwt.integration.repository")
    public class DatasourceConfig {

        @Bean
        public DataSource datasource() throws PropertyVetoException {
               final DriverManagerDataSource dataSource = new DriverManagerDataSource();
               dataSource.setDriverClassName("com.mysql.jdbc.Driver");
               dataSource.setUrl("jdbc:mysql://localhost:3306/fdb?createDatabaseIfNotExist=true");
               dataSource.setUsername("root");
               dataSource.setPassword("");
               return dataSource;
    }
   ....
   ....
   ....
kj007 :

Once you have defined data source properties in application.properties in @SpringBootApplication it will auto configure your datasource, so you can remove DataSource configuration. But still if you want to customize your data source configuration then below should work as Environment should give you access of properties:

@Configuration
@PropertySource(value= {"classpath:application.properties"})
public class DatasourceConfig {

    @Autowired
    Environment environment;

    @Bean
    public DataSource datasource() throws PropertyVetoException {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(environment.getProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.datasource.password"));
        return dataSource;
    }
}

Or if you don't want to access properties via Environment, you can access by @Value

  @Value("${spring.datasource.driver-class-name}")
    private String driverName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String password;

    @Bean
    public DataSource datasource() throws PropertyVetoException {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        return dataSource;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80420&siteId=1