我是Spring Boot的新手。我必须升级使用Java构建的系统,并且必须使用spring boot转换以下代码段
String message = propertiesService.getProperty("app.directory.errorcode." + errorNumber);
其中propertiesService
用于读取application.properties
。
现在,我如何像以前一样在Spring Boot中阅读此内容,因为我以前在声明类变量的地方使用static关键字声明了属性。
@Value("${app.directory.errorcode.fatal}")
private static String fatalCode;
我需要生成属性名称并动态读取它
您不能直接将值注入静态变量,您将需要使用instance setter方法将其注入。示例代码:
private static String fatalCode;
@Value("${app.directory.errorcode.fatal}")
public void setFatalCode(String fatal) {
fatalCode = fatal;
}
您可以使用org.springframework.core.env.Environment
类来实现。
示例:
@SpringBootApplication
public class Example {
// autowire the Environment
@Autowired
private Environment env;
private static String fatalCode;
public static someMethod(String errorNumber) {
fatalCode = env.getProperty("app.directory.errorcode." + errorNumber);
}
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
我希望这会对您有所帮助。
谢谢:)