spring boot: how to configure datasource from application properties
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;
}