1

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?

akash patel
  • 163
  • 9
  • Declare the Properties variable as a public static class member of your Main class. Also, there is [another way](https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot) , if you just want to access properties from your app.properties file. – dope Sep 23 '20 at 17:28

2 Answers2

1

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.

Suraj Gautam
  • 1,524
  • 12
  • 21
0

You could think about static methods... or maybe think about the singleton pattern.

MrBrightside
  • 119
  • 1
  • 9