如何使用属性作为变量?

时间:2015-12-08 13:48:39

标签: java properties

例如我有财产:project.password.time=123456

然后我想在某个类中将它用作变量。

例如,Long time = {my property}

这不起作用:(java.lang.NumberFormatException:null)

Long time = Long.valueOf(System.getProperty("project.password.time"))  

我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果你有一个文件,请说config.properties,那么你可以

    final Properties props = new Properties();
    final String propertyFileName = "config.properties";
    final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertyFileName);

    if (inputStream != null) {
        props.load(inputStream);
    } else {
        throw new FileNotFoundException("Property file not found " + propertyFileName);
    }
    System.out.println(props.getProperty("project.password.time"));

系统println将打印值123456

由于我不确定你的需求是什么,这似乎是最简单的答案。 正如Jiri所注意到的,您希望将属性propertyName = value放在文件中,因为属性文件就像地图一样。

答案 1 :(得分:0)

我只需要添加

@Autowired
private Environment env;

    Long time = Long.valueOf(env.getProperty("project.password.time"));
相关问题