如何为不同的机器设置不同的属性文件?

How to have different properties file for different machines?

所以我在一个小型学校项目的团队中工作,我们正在使用 apache 开发 java/jsp 网络应用程序。我创建了简单的 properties.config 文件,以便我可以存储值稍后使用它们,它看起来像这样:

home_url = http://localhost:8080/to3/
to3_path = C:/Users/User2/Documents/workspace/TO-3
db_url = jdbc:mysql://localhost:3306/to3?useUnicode=true&characterEncoding=UTF-8

我遇到的问题是当我提交它并且有人进行结帐时他们必须更改 url-s 和路径的值以使其适合他们的机器..我听说我可以制作一个自定义属性文件如果它识别某些机器,将覆盖这些默认值,但我不知道该怎么做。

提前感谢大家的帮助。

不要提交项目设置。将它们放入 .gitignore 并提交一份副本(例如 properties.config.sample)。确保与您添加的任何新密钥保持同步,但每个开发人员都应该制作自己的 untracked 副本。

正如 Amadan 指出的那样,您不应该提交项目属性。我的建议是创建一个扩展名为 .properties 的文件,并将您的属性放入其中。要在 java 中使用此文件,您可以创建一个 class 类似

public class MyProperties{
    private String homeUrl = "";
    private String to3Path = "";
    private String dbPath = "";

    private final String configPath = System.getProperty("user.home") + File.separator + "my-props.properties";

    public void loadProperties(){
        try {
            Properties prop = new Properties();
            InputStream input = null;
            File filePath = new File(configPath);
            input = new FileInputStream(filePath);
            // load a properties file
            prop.load(input);
            homeUrl = prop.getProperty("home_url");
            to3Path = prop.getPropert("to3_path");
            dbPath = prop.getProperty("db_url");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    // getters & setters 
}

然后在您的应用中您可以

MyProperties props = new MyProperties();
props.loadProperties();
String homeUrl = props.getHomeUrl();

System.getProperty("user.home") 将根据 OS 给出主路径。 例如在 windows 中,这是路径 C:\Users\yourName

这样您的所有 co-workers 都可以将他们自己的属性放在他们个人电脑的主路径中,您将能够在没有冲突的情况下工作。