Karthik Anand
Karthik Anand

Reputation: 1

Loading properties from external sources in spring

Here is my use case:

I have only the db.userName available in properties file. I don't have db.password available in my local property file.

In my java class i have

Class A {

@Value("${db.userName}")
String userName;

@Value("${db.password}")
String  userPassword;

}

I would like to resolve db.password by making a REST call to an external service which stores the passwords in a centralized place.

How do I do this in Spring 3.1 ? I tried extending PropertySourcesPlaceholderConfigurer with no luck.

Upvotes: 0

Views: 384

Answers (2)

user4046031
user4046031

Reputation:

  • Consume rest service in getter, although I recommend you to implement service for that.

    private String getUserPassword(){
        final String uri = "url/get-db-paswword";
    
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(uri, String.class);
    }
    

Upvotes: 0

DimaSan
DimaSan

Reputation: 12724

Create app.properties file under resources folder and put there your data:

db.userName=karthik
db.password=

Then use it like:

@Configuration
@PropertySource("classpath:/app.properties")
public class A {

    @Value("#{db.userName}")
    String userName;

    @Value("#{db.password}")
    String userPassword;
}

Read some more info on Spring Doc.


You can also create your database configuration class and configure DataSource bean like:

@Configuration
@PropertySource("app.properties")
public class DataConfig {
    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername(env.getProperty("db.username"));
        ds.setPassword(env.getProperty("db.password"));
        return ds;
    }
}

Upvotes: 1

Related Questions