一个对象如何在Java中对所有类可用?

huangapple go评论62阅读模式
英文:

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

问题

我正在创建一个包含许多Java类的应用程序。为了存储可配置信息,比如用户名、网址、文件路径等,我正在使用resources/app.properties文件。

为了从这个文件中读取值,我正在使用以下代码

InputStream input = new FileInputStream("../resources/app.properties");

Properties prop = new Properties();

prop.load(input);

System.out.println("print the url" + prop.getProperty("username"));

正如我们从代码中可以看到的那样,要从app.properties文件中读取任何属性,我们需要prop对象。

我们是否可以以这样的方式编写代码,即在主类中只需编写前3行一次,然后我们可以在整个应用程序的任何类中调用**prop.getProperty("username")**呢?

英文:

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?

答案1

得分: 1

很简单。

定义配置,如下:

@Configuration
public class TestConfiguration {

    @Value("classpath:test.properties")
    private Resource resource;

    @SneakyThrows // 这是来自 lombok 依赖。你可以处理异常
    @Bean
    public Properties getProperties() {
        Properties properties = new Properties();
        properties.load(this.resource.getInputStream());
        return properties;
    }

}

在需要的地方自动装配这个类。

@Autowired
private TestConfiguration configuration;

使用:this.configuration.getProperties().getProperty("username") 来获取用户名,其他字段也同理。

通过这种方式,你可以实现单例设计模式。

英文:

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.

答案2

得分: 0

你可以考虑静态方法...
或者考虑单例模式。

英文:

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

huangapple
  • 本文由 发表于 2020年9月24日 01:16:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64033098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定