【问题标题】:Inject application properties without Spring在没有 Spring 的情况下注入应用程序属性
【发布时间】:2017-04-11 16:08:31
【问题描述】:

我想要一种简单的、最好是基于注解的方法来将外部属性注入到 java 程序中,而不使用 spring 框架 (org.springframework.beans.factory.annotation.Value;)

SomeClass.java

@Value("${some.property.name}")
private String somePropertyName;

application.yml

some:
  property:
    name: someValue

在标准库中有推荐的方法吗?

【问题讨论】:

  • 不,这就是 Spring 的功能存在的原因。
  • 既然我想要一个非弹簧的答案,我不应该包含spring-* 标签

标签: java spring properties annotations spring-annotations


【解决方案1】:

我最终使用了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.properties

someKey: 2

我不想将我的库变成 Spring 应用程序(我想要 @Value 注释,但没有应用程序上下文 + @Component、额外的 bean、额外的 Spring 生态系统/行李,这在我的项目中没有意义) .

【讨论】:

  • 感谢您回答问题。我知道这是一个不好的评论,但很少有人回来帮助可能有同样问题的其他人。所以谢谢。
  • 你是说你用它来阅读“application.yml”(强调yml),还是你用这个库和(恢复)来阅读application.properties文件?
  • 我可能是使用这个库从 application.properties 中读取的,当时我认为 yml 与属性对我来说并不重要,但我不记得了。
  • 好的。是的,我喜欢 application.yml 的语法,但是 spring-baggage 对那个组件来说实在是太多了。 @AnnotationEasyPeezey。
  • 我很惊讶这是有这么多赞成票的公认答案。最初的问题似乎是要求一种纯粹的 JSR-330 方式来实现 @Value 在 Spring 中所做的事情,例如@Inject @Named("some.property.name") private String somePropertyName; 之类的东西(任何实现 JSR-330 的框架实际上都不支持 AFAIK)。此外,接受的答案不是基于注释的,而且,甚至根本不使用依赖注入。在我看来,这根本不能回答这个问题。
猜你喜欢
  • 2018-05-15
  • 2018-07-12
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 2015-03-16
  • 2014-05-24
相关资源
最近更新 更多