不使用Spring注入应用程序属性

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生态系统/行李,这在我的项目中没有意义).

  • 谢谢你回答你的问题。我知道这是一个不好的评论,但很少有人回来帮助那些可能遇到相同问题的人。那谢谢啦。 (3认同)
  • 我很惊讶这是得到这么多赞成票的接受答案。最初的问题似乎是要求一种纯粹的 JSR-330 方法来实现 Spring 中的 `@Value` 功能,例如 `@Inject @Named("some.property.name") private String somePropertyName;` (据我所知)实际上,任何实现 JSR-330 的框架都不支持)。此外,接受的答案不是基于注释的,而且甚至根本不使用依赖注入。在我看来,这根本不能回答问题。 (2认同)

小智 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)

  • 这应该是公认的答案!这段代码运行得很好。如果你可以用 10 行自己编写的代码来完成它,为什么还要包含整个库呢? (2认同)