app.configと同等のJava?
-
03-07-2019 - |
質問
.NETのApp.Configに相当するJavaはありますか?
ない場合は、アプリの設定を保持する標準的な方法があり、アプリの配布後に設定を変更できますか?
解決
WebAppの場合、web.xmlを使用してアプリケーション設定を保存できます。
それ以外は、プロパティプロパティファイルを読み書きするクラス。
もご覧ください。 Preferences クラス。システムおよびユーザー設定の読み取りと書き込みに使用されます。これは抽象クラスですが、 userNodeForPackage(ClassName.class)
および systemNodeForPackage(ClassName.class)
を使用して適切なオブジェクトを取得できます。
他のヒント
Properties
クラスの使用に関する@Powerlordの提案(+1)をサンプルコードに含めるには:
public class SomeClass {
public static void main(String[] args){
String dbUrl = "";
String dbLogin = "";
String dbPassword = "";
if (args.length<3) {
//If no inputs passed in, look for a configuration file
URL configFile = SomeClass.class.getClass().getResource("/Configuration.cnf");
try {
InputStream configFileStream = configFile.openStream();
Properties p = new Properties();
p.load(configFileStream);
configFileStream.close();
dbUrl = (String)p.get("dbUrl");
dbLogin = (String)p.get("dbUser");
dbPassword = (String)p.get("dbPassword");
} catch (Exception e) { //IO or NullPointer exceptions possible in block above
System.out.println("Useful message");
System.exit(1);
}
} else {
//Read required inputs from "args"
dbUrl = args[0];
dbLogin = args[1];
dbPassword = args[2];
}
//Input checking one three items here
//Real work here.
}
}
次に、コンテナのルート(jarファイルの上部など)に、次の内容のファイル Configuration.cnf
を配置します:
#Comments describing the file
#more comments
dbUser=username
dbPassword=password
dbUrl=jdbc\:mysql\://servername/databasename
これは完璧ではありませんが(改善点に興味があります)、現在のニーズには十分です。
単純な方法は、すべての設定を含むプロパティファイル(myapp.propertiesなど)を用意することです。設定を行うための非常に高度な方法ではありませんが、十分であるか、独自のXMLベースのセットアップを使用できます。データベースなどから取得します。
所属していません StackOverflow