我有spring引导应用程序,用户在其中发送参数,并且基于这个参数,应该得到配置。
我创建了文件名配置类型“Configration_Types.properies”,现在如何读取基于参数传递的配置--我不想创建数据库来查找它?
Type1=Type1
Type1.width=60
Type1.heght=715
Type2=Type2
Type2.width=100
Type2.heght=720
Type3=Type3
Type3.width=100
Type3.heght=700
Type4=Type4
Type4.width=450
Type4.heght=680
Type5=Type5
Type5.width=270
Type5.heght=750例如,pass type4应该获得配置
Type4
450
680
发布于 2018-04-03 09:27:44
功能可以是这样的:
public void readPropertyByType(String type)
{
InputStream input = null;
try
{
Properties prop = new Properties();
// if your type is Type4, the typeKey will be Type4. for compare data
String typeKey = type + ".";
String filename = "config.properties";
input = new FileInputStream(filename);
prop.load(input);
String typeInformation = "";
Enumeration< ? > e = prop.propertyNames();
while (e.hasMoreElements())
{
String key = (String)e.nextElement();
if (key.indexOf(typeKey) > 0)
{
typeInformation = typeInformation + prop.getProperty(key);
}
}
System.out.println("The data of type " + type + "is :" + typeInformation);
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}希望能帮上忙。
--更新--
属性文件可以是这样的:
Type4.width=450
Type4.heght=680
Type5.width=450
Type5.heght=680
Type4=450,680
Type5=450,680
取决于每个选项,当您获得预期的数据时,您可以中断while循环。
发布于 2018-04-03 10:21:51
如果您可以修改属性文件Configration_Types.properies,如:-
type[0].width=60
type[0].heght=715
type[1].width=100
type[1].heght=720
type[2].width=100
type[2].heght=700
type[3].width=450
type[3].heght=680
type[4].width=270
type[4].heght=750使用属性文件中的属性值的类是:-
@Component
@ConfigurationProperties("type") // prefix type, find type.* values
public class GlobalProperties {
private List<Type> type = new ArrayList<Type>();
//getters and setters
public static class Type
{
private int width;
private int heght;
// getter setter
}而且,根据用户参数,您可以从arraylist访问值。
希望这种帮助:
https://stackoverflow.com/questions/49625808
复制相似问题