![](/img/trans.png)
[英]Set Spring Boot application.properties based on Environment Variable
[英]Access Environment based application.properties file in class not managed by spring
我正在開發版本為 2.1.6.RELEASE 和 xslt 1.0 的 Spring Boot 項目。
我有一個類,它有一組靜態方法,用於使用與應用程序相關的自定義邏輯生成一組 URL。
public class URLGenerator{
public static String generateURLA(String param1,String param2,String param3)
{
String restServiceUrl=<acess url from application.properties>
//code to invoke third party service
RestTemplate restTemplate=new RestTemplate();
String url=restTemplate.invoke()
return url;
}
}
在上述方法中,我必須對第三方服務進行休息調用以檢索最終 URL。 調用服務的 URL 因環境而異,因此我將 URL 存儲在 application-{env}.properties 文件中。
我將無法將上述方法更改為非靜態,因為有多個 xsl 文件調用了上述方法。
在不受 Spring 管理的類中訪問基於環境的 application.properties 文件的最佳方法是什么?
您可以簡單地自動裝配Environment
並獲取屬性:
@Autowired
private Environment env;
public void method() {
String url = env.getProperty("service.url");
// ...
}
如果它不是一個 bean,你可以簡單地創建一個服務,這樣做:
@Service
class PropertyService implements InitializingBean {
@Autowired
private Environment env;
private static PropertyService instance;
public void method() {
String url = env.getProperty("service.url");
// ...
}
@Override
public void afterPropertiesSet() throws Exception {
instance = this;
}
public static PropertyService get() {
return instance;
}
}
您可以在這里使用普通的舊屬性。
final Properties props = new Properties();
props.load(new FileInputStream("/path/application.properties"));
props.getProperty("urls.foo"));
props.getProperty("urls.bar"));
或者
final Properties props = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
props.load(is);
props.getProperty("urls.foo"));
props.getProperty("urls.bar"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.