akash patel
akash patel

Reputation: 173

How an object can be available to all classes in java?

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

Answers (2)

Suraj Gautam
Suraj Gautam

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

MrBrightside
MrBrightside

Reputation: 119

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

Upvotes: 0

Related Questions