Reputation: 173
I am creating an application with many java classes. for keeping the configurable information like username, urls', file paths etc, I am using resources/app.properties file.
For reading values from this file, I am using below code
InputStream input = new FileInputStream("../resources/app.properties");
Properties prop = new Properties();
prop.load(input);
System.out.println("print the url" + prop.getProperty("username"));
as we can see from the code, for reading any property from app.properties file, we need prop object.
can we write this code in such a way that we just need to write first 3 lines once in the code in the main calss and then we can call prop.getProperty("username") from any class in our whole application?
Upvotes: 1
Views: 683
Reputation: 1590
It's pretty simple.
Define configuration, like
@Configuration
public class TestConfiguration {
@Value("classpath:test.properties")
private Resource resource;
@SneakyThrows // this is from lombok dependency. You can handle exception
@Bean
public Properties getProperties() {
Properties properties = new Properties();
properties.load(this.resource.getInputStream());
return properties;
}
}
Autowire this class wherever you need it.
@Autowired private TestConfiguration configuration;
Use: this.configuration.getProperties().getProperty("username")
to get username and same for other fields.
By doing this way, you can achieve a singleton design pattern.
Upvotes: 1
Reputation: 119
You could think about static methods... or maybe think about the singleton pattern.
Upvotes: 0