![](/img/trans.png)
[英]Spring Boot - inject from application.yml and application.properties
[英]Inject application properties without Spring
我想要一種簡單的、最好是基於注釋的方法來將外部屬性注入 java 程序,而不使用 spring 框架( org.springframework.beans.factory.annotation.Value;
)
SomeClass.java
@Value("${some.property.name}")
private String somePropertyName;
應用程序.yml
some:
property:
name: someValue
在標准庫中有推薦的方法嗎?
我最終使用apache commons配置 :
pom.xml中:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>
SRC /.../ PropertiesLoader.java
PropertiesConfiguration config = new PropertiesConfiguration();
config.load(PROPERTIES_FILENAME);
config.getInt("someKey");
/src/main/resources/application.properties
someKey: 2
我不想把我的庫變成Spring應用程序(我想要@Value
注釋,但沒有應用程序上下文+ @Component
,額外的bean,額外的Spring生態系統/行李,這在我的項目中沒有意義)。
在此處定義應用程序屬性/src/main/resources/application.properties
定義 PropertiesLoader class
public class PropertiesLoader {
public static Properties loadProperties() throws IOException {
Properties configuration = new Properties();
InputStream inputStream = PropertiesLoader.class
.getClassLoader()
.getResourceAsStream("application.properties");
configuration.load(inputStream);
inputStream.close();
return configuration;
}
}
在所需的 class 中注入屬性值,如下所示,
Properties conf = PropertiesLoader.loadProperties();
String property = conf.getProperty(key);
有人告訴我java中有標准的DI庫:javax.inject(JSR-330)包。 但是我沒有在jdk 1.8(但是一個名為javax.injtct-1.jar的jar)中找到它。
我在谷歌上偶然發現了這個答案,但我並不滿意。
最后,我創建了環境 class,它使用了來自@Stone 答案的應用程序屬性和硬編碼的環境變量。 但我仍在尋找更好的選擇,因為我無法修改 application.propeties 中的 ENV_VARIABLE 名稱,這正是我最初想要的。
public class EnvironmentPlainJava {
public int httpsPort() {
return Integer.parseInt(PropertiesLoader.loadProperties().getProperty("https.port"));
}
public String keyStorePath() {
return System.getenv("KEY_STORE_PATH");
}
}
For reference, here is an idiomatic Kotlin version of the @Stone code (using ClassPathResource
Spring utility class - doesn't require running Spring:):
fun loadProperties(properties: String = "application.properties"): Properties =
ClassPathResource(properties).inputStream.use { inputStream ->
Properties().also {
it.load(inputStream)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.