Andrei Amarfii
Andrei Amarfii

Reputation: 725

Spring load specific properties into a properties object

My application.propertiescontains the following properties :

db.username = ...
db.password = ...
db.timeout = ...

rest.client.username = ...
rest.client.password = ...
rest.client.timeout = ...

I would like to load only the rest client's properties into a configuration

@Configuration
public class Config {

....

private Properties restProperties; // << here should go 3 properties with prefix rest.client

}

Any way to do it in Java Based Configurations ?

Upvotes: 0

Views: 853

Answers (1)

TwiN
TwiN

Reputation: 3824

If you move your all of your rest.client properties into their own properties file (e.g. restclient.properies), you can use PropertiesLoaderUtils:

Resource resource = new ClassPathResource("/restclient.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);

Alternatively, you can use @ConfigurationProperties, as seen here, but it won't be a Properties object, but rather, an object that you define yourself.

Also, I feel like it might be worth mentioning that you can add

@Autowired
private Environment env;

and access any properties by using

env.getProperty("your.property.here")

Upvotes: 1

Related Questions