试了很多种方法,@VALUE,ENVIROMENT,都不行,最后发现用这种可以
在Java中,你可以使用java.util.Properties
类来直接获取application.properties
文件中的值。以下是一个简单的例子,演示如何读取application.properties
文件中的属性:
首先,确保你的application.properties
文件在类路径下,例如在src/main/resources
目录中。
然后,使用java.util.Properties
类加载并读取这个文件:
import java.io.InputStream;
import java.util.Properties;
public class ApplicationProperties {
private static final Properties properties = new Properties();
static {
try {
InputStream inputStream = ApplicationProperties.class.getClassLoader().getResourceAsStream("application.properties");
if (inputStream != null) {
properties.load(inputStream);
} else {
throw new RuntimeException("Could not find application.properties");
}
} catch (Exception e) {
throw new RuntimeException("Error loading application.properties", e);
}
}
public static String getProperty(String key) {
return properties.getProperty(key);
}
}
使用这个类,你可以通过调用getProperty
方法来获取属性值:
public class Main {
public static void main(String[] args) {
String someProperty = ApplicationProperties.getProperty("some.property.key");
System.out.println(someProperty);
}
}
确保你的application.properties
文件中包含了你想要获取的属性,例如:
some.property.key=someValue
当你运行Main
类的main
方法时,它将输出application.properties
中对应some.property.key
的值。