Kis*_*nki 4 java class spring-boot
我知道如何访问Java Spring boot 中的类application.properties中的值@Service,如下所示
@Service
public class AmazonClient {
@Value("${cloud.aws.endpointUrl}")
private String endpointUrl;
}
Run Code Online (Sandbox Code Playgroud)
但我正在寻找一个选项来直接在任何类中访问该值(没有 @Service 注释的类)
例如
public class AppUtils {
@Value("${cloud.aws.endpointUrl}")
private String endpointUrl;
}
Run Code Online (Sandbox Code Playgroud)
但这又回来了null。任何帮助,将不胜感激。我已经读过这里但没有帮助。
没有“神奇”的方法可以将属性文件中的值注入到非 bean 的类中。您可以在类中定义一个静态java.util.Properties字段,在加载类时手动从文件中加载值,然后使用该字段:
public final class AppUtils {
private static final Properties properties;
static {
properties = new Properties();
try {
ClassLoader classLoader = AppUtils.class.getClassLoader();
InputStream applicationPropertiesStream = classLoader.getResourceAsStream("application.properties");
applicationProperties.load(applicationPropertiesStream);
} catch (Exception e) {
// process the exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21525 次 |
| 最近记录: |