eal*_*nso 5 java spring annotations properties spring-annotations
我想要一个简单的,最好是基于注释的方法将外部属性注入到java程序中,而不使用spring framework(org.springframework.beans.factory.annotation.Value;)
SomeClass.java
@Value("${some.property.name}")
private String somePropertyName;
Run Code Online (Sandbox Code Playgroud)
application.yml
some:
property:
name: someValue
Run Code Online (Sandbox Code Playgroud)
是否有推荐的方法在标准库中执行此操作?
eal*_*nso 11
我最终使用apache commons配置:
pom.xml中:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
SRC /.../ PropertiesLoader.java
PropertiesConfiguration config = new PropertiesConfiguration();
config.load(PROPERTIES_FILENAME);
config.getInt("someKey");
Run Code Online (Sandbox Code Playgroud)
/src/main/resources/application.properties
someKey: 2
Run Code Online (Sandbox Code Playgroud)
我不想把我的库变成Spring应用程序(我想要@Value注释,但没有应用程序上下文+ @Component,额外的bean,额外的Spring生态系统/行李,这在我的项目中没有意义).
小智 11
在此处定义应用程序属性/src/main/resources/application.properties
定义PropertiesLoader类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在所需的类中注入属性值,如下所示,
Properties conf = PropertiesLoader.loadProperties();
String property = conf.getProperty(key);
Run Code Online (Sandbox Code Playgroud)