I created new Enviroment in SpringConfig file:
private final Environment environment;
@Autowired
public SpringConfig(ApplicationContext applicationContext, Environment environment) {
this.applicationContext = applicationContext;
this.environment = environment;
}
And file database.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/first_db
username=root
password=1234
Created dataSource bean
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Objects.requireNonNull(environment.getProperty("driver")));
dataSource.setUrl(environment.getProperty("url"));
dataSource.setUsername(environment.getProperty("username"));
dataSource.setPassword(environment.getProperty("password"));
return dataSource;
}
It gave me error and I checked what enviroment.getProperty returns me. It showed me:
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/first_db
PC // my PC name
1234
So why does enviroment returns me my Pc's name? How do I know what properties are already assigned?
Agree with the comment from Alex R about the %USERNAME%
variable having a higher priority. Using a prefix for values in your .properties
files is a good practice and will help you avoid a lot of conflicts like this.
Alternatively, you can use the ResourceBundle
class.
With database.properties
at the top level of your Java resources (if not at the top level, just provide the path to the database.properties
file), the snippet below will give you what you need:
final ResourceBundle bundle = ResourceBundle.getBundle("database");
final String username = bundle.getString("username");
final String password = bundle.getString("password");