【问题标题】:Config-file for JavaFX-ProjectJavaFX 项目的配置文件
【发布时间】:2021-12-31 19:29:39
【问题描述】:

我想在我的 JavaFX 项目中添加一个仅包含项目配置数据的文件或类,例如数据库、系统路径等的访问数据。你会怎么做? 只是在普通的课堂上写所有东西?肯定有更好的方法吧?

【问题讨论】:

  • 资源、属性、偏好、数据库等;您的要求可能有助于在设计备选方案中进行选择。
  • 使用属性文件。见stackoverflow.com/questions/8285595/…
  • 谢谢大家,我去看看属性的东西。
  • 如果你要使用数据库和配置属性,那么我推荐integrating JavaFX and SpringBoot。 spring.io 和 baeldung 上有很多教程解释了如何使用 spring 数据和配置,例如 properties and Springspring dara。 Spring 并不适合所有人,因此请根据您的要求进行衡量。
  • 嗨,我也认为 Spring 是最好的选择。我的项目很小,只是给老板们做个说明。以后等我能继续做下去的时候,我肯定会和Spring一起走的。但是我仍然需要学习一点,因为到目前为止我只是将编程作为一种爱好。顺便说一句,这些属性效果很好,并且已经内置。再次感谢您的好提示。

标签: java javafx


【解决方案1】:

你说得对,我当然很乐意这样做。 首先,我在项目文件夹中创建了一个属性文件,并将其命名为 app.properties:

db_url=jdbc:mysql://localhost:3306/db name
db_user=user name
db_pwd=secret password
instructions_folder=/home/username/documents/

然后我创建了一个类来加载属性并使它们在整个项目中可用。

public class AppProperties {

    // FILENAME = Path to properties-file
    // Store and protect it where ever you want
    private final String FILENAME = "app.properties";
    
    private static final AppProperties config_file = new AppProperties();
    private Properties prop = new Properties();
    private String msg = "";

    private AppProperties(){
        InputStream input = null;

        try{
            input = new FileInputStream(FILENAME);

            // Load a properties
            prop.load(input);
        }catch(IOException ex){
            msg = "Can't find/open property file";
            ex.printStackTrace();
        }finally{
            if (input != null){
                try{
                    input.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }

        }
    }

    public String getProperty (String key){
        return prop.getProperty(key);
    }

    public String getMsg () {
        return msg;
    }

    // == Singleton design pattern == //
    // Where ever you call this methode in application
    // you always get the same and only instance (config_file)
    public static AppProperties getInstance(){
        return config_file;
    }
}

在我进行数据库查询的 DBUtilitis 类中,我现在将属性加载到最终变量中并在查询方法中使用它们。

private static final String db_url = AppProperties.getInstance().getProperty("db_url");
    private static final String db_user = AppProperties.getInstance().getProperty("db_user");
    private static final String db_pwd = AppProperties.getInstance().getProperty("db_pwd");

如果我没有完全误解这一点,属性文件的优点是它们可以存储和保护在服务器的某个地方。我希望解决方案不是完全错误的 - 无论如何它运作良好。我总是很高兴收到建议和/或改进。

【讨论】:

  • 更多关于财产安全here.
  • 谢谢垃圾神。非常有趣的东西。
  • encrypting properties 的解决方案(如果需要)。
  • 也很有趣。谢谢jewelsea
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 2018-12-18
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
相关资源
最近更新 更多