Configure DataSource programmatically in Spring Boot
You can use DataSourceBuilder
if you are using jdbc
starter. Also, in order to override the default autoconfiguration bean you need to mark your bean as a @Primary
In my case I have properties starting with datasource.postgres
prefix.
E.g
@ConfigurationProperties(prefix = "datasource.postgres")
@Bean
@Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.build();
}
If it is not feasible for you, then you can use
@Bean
@Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("")
.password("")
.url("")
.driverClassName("")
.build();
}
Spring Boot DataSource Configuration
It is in context of Externalization not Datasource specifc. In which you put your application related parameters outside the code files using .properties, .xml or .yml config files. It allows you to configure your application without compiling. If you want to change, you just have to change the values in config file and application will behave as per provided values no need to recompile.
We normally externalized properties for Datasource, Connection Pool, Logging configuration, Endpoints and many more.
For example in case of Datasource configuration you can pass DB url, username, password in external configuration file instead of code and refer those values through keys. So in future if the datasource url changes you just have to make change in config file. Otherwise you would have to make changes in code which would need recompile and rebuild your application for changes to be effective.
But also take into consideration of sensitivity of values too for which there are some techniques which i believe outside the scope of this question.
How to configure spring datasource programmatically in web based app which uses JdbcTemplate and SpringDaoSupport?
In your dispatcher-servlet.xml
you need to make sure you have either:
<context:annotation-config/>
<bean class="com.example.AppConfig" />
or
<context:component-scan base-package="com.example"/>
How to create Custom DataSource in Spring Boot + Spring Data
No need to exclude the built in autoconfiguration.
In you application.yml
myapp:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mydb?autoReconnect=true&characterEncoding=utf8
username: myuser
# make sure you exclude password from here
And in your configuration:
// all the other datasource properties will be applied from "myapp.datasource" except password because you excluded it
@ConfigurationProperties(prefix = "myapp.datasource")
@Bean
@Primary // this will override the datasource autoconfiguration and use your own everywhere
public DataSource dataSource() {
String password = retrieveMyPasswordSecurely();
return DataSourceBuilder
.create()
.password(password)
.build();
}
how can spring boot get spring datasource config value from os environment variable?
In most cases, any punctuation like those hyphens can be converted to underscores for the system environment variable, e.g. SPRING_DATASOURCE_DRIVER_CLASS_NAME
. In some earlier versions of Spring this wasn't exactly standardized yet and some properties might drop the hyphens entirely, e.g. SPRING_DATASOURCE_DRIVERCLASSNAME
.
Another approach: set the system env var, JAVA_TOOL_OPTIONS
, with any desired Java/JVM options like:
JAVA_TOOL_OPTIONS=-server -Xmx1g -Dspring.datasource.driver-class-name=com.mysql.jdbc.Driver
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;
}
Related Topics
Invalid Signature File Digest for Manifest Main Attributes Exception While Trying to Run Jar File
Difference Between Wait and Blocked Thread States
Spring Cron Expression for Every Day 1:01:Am
How to Change the Color of Titlebar in Jframe
Totally Confused with Java.Exe
Java Stanford Nlp: Part of Speech Labels
Org.Postgresql.Util.Psqlexception: Fatal: Sorry, Too Many Clients Already
In Which Thread Do Completablefuture's Completion Handlers Execute
Good Examples Using Java.Util.Logging
Eclipse Reading Stdin (System.In) from a File
How to Create an Instance of Inner Class Using Java Reflection
Java User.Home Is Being Set to %Userprofile% and Not Being Resolved
What's the Difference Between Getrequesturi and Getpathinfo Methods in Httpservletrequest
Method Calls Inside a Java Class Return an "Identifier Expected After This Token" Error