在没有 Spring 的情况下注入应用程序属性
Inject application properties without Spring
我想要一种简单的、最好是基于注释的方法来将外部属性注入 java 程序,而不使用 spring 框架 (org.springframework.beans.factory.annotation.Value;
)
SomeClass.java
@Value("${some.property.name}")
private String somePropertyName;
application.yml
some:
property:
name: someValue
标准库中有推荐的方法吗?
我最终使用了 apache commons configuration:
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.属性
someKey: 2
我不想将我的库变成 Spring 应用程序(我想要 @Value
注释,但没有应用程序上下文 + @Component
,额外的 beans,额外的 Spring ecosystem/baggage 这在我的项目中没有意义)。
在此处定义应用程序属性 /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 = configuration.getProperty(key);
我想要一种简单的、最好是基于注释的方法来将外部属性注入 java 程序,而不使用 spring 框架 (org.springframework.beans.factory.annotation.Value;
)
SomeClass.java
@Value("${some.property.name}")
private String somePropertyName;
application.yml
some:
property:
name: someValue
标准库中有推荐的方法吗?
我最终使用了 apache commons configuration:
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.属性
someKey: 2
我不想将我的库变成 Spring 应用程序(我想要 @Value
注释,但没有应用程序上下文 + @Component
,额外的 beans,额外的 Spring ecosystem/baggage 这在我的项目中没有意义)。
在此处定义应用程序属性 /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 = configuration.getProperty(key);