我想使用 spring boot 转换以下代码片段。
String message = propertiesService.getProperty("app.directory.errorcode." + errorNumber);
其中propertiesService
用于读取application.properties
。
如何在 Spring 启动中阅读它,因为我之前已经声明了属性 在声明类变量的地方使用 static 关键字?
@Value("${app.directory.errorcode.fatal}")
private static String fatalCode;
我需要生成属性名称并动态读取它。
您可以使用包org.springframework.core.env
中的类Environment
来实现此目的。
例:
@SpringBootApplication
public class Example {
// autowire the Environment
@Autowired
private Environment environment;
private static String fatalCode;
public void someMethod(String errorNumber) {
fatalCode = environment.getProperty("app.directory.errorcode." + errorNumber);
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
我希望这对你有所帮助。
谢谢:)