【问题标题】:Import a .properties file into a java.util.Properties type variable in Configuration class via annotation通过注解将 .properties 文件导入到 Configuration 类中的 java.util.Properties 类型变量中
【发布时间】:2022-01-24 10:09:00
【问题描述】:

我正在将我的 java 应用程序从 Spring 迁移到 Spring Boot,并且我想消除基于 xml 的配置并完全迁移到 基于注释的配置。 p>

我想将属性文件按原样加载到 java.util.Properties 类型变量中。

@Configuration
public class ApplicationConfig
{
  // inject the file into this variable
  private Properties myOtherProp;
}

在基于 xml 的配置中,这是通过以下方式在一行中完成的:

<util:properties id="myOtherProp" location="classpath:myOtherProperties.properties"/>

我目前实现这一目标的方式是这样做:

@Configuration
public class ApplicationConfig
{
  private Properties myOtherProp;

  private void myMethodToInitialiseMyOtherProp()
  {
    myOtherProp = new Properties();
    myOtherProp.load(getClass().getClassLoader().getResourceAsStream("myOtherProperties.properties"));
  }

  @Bean
  public myClass beanWhichUsesTheOtherProp()
  {
    myMethodToInitialiseMyOtherProp();
    return new myClass(myOtherProp);
  }
}

我正在寻找一种解决方案来在一行中执行此操作,就像 @Value 对原始数据类型所做的那样。 或者至少能够调用我的方法 - myMethodToInitialiseMyOtherProp(),我在其中声明了 Properties 变量,这样我就可以消除在任何地方第一次使用它之前记住调用函数来初始化变量的开销。

我知道如何注入在 myOtherProperties.properties 中声明的各个字段,但这不是我想要在这里实现的。我希望将整个文件加载到变量中 - 类型为属性的 myOtherProp。

类似这样的:

@Configuration
public class ApplicationConfig
{
  // inject the file into this variable
  @Something-Like-Value-Annotation-To-Inject-The-File-In-One-Line
  // OR //
  @Some-Way-To-Call-myMethodToInitialiseMyOtherProp()
  private Properties myOtherProp;
}

【问题讨论】:

    标签: java spring spring-boot spring-annotations


    【解决方案1】:

    你可能想参考这个。在您的情况下会有所帮助。 链接:https://www.baeldung.com/properties-with-spring

    将属性声明为:

    @Configuration
    @PropertySource("classpath:foo.properties")
    public class PropertiesWithJavaConfig {
        //...
    }
    

    在其他类中使用它们: 示例 1:

    @Value( "${jdbc.url}" )
    private String jdbcUrl;
    

    示例 2:

    @Autowired
    private Environment env;
    ...
    dataSource.setUrl(env.getProperty("jdbc.url"));
    

    注意:代码 sn-ps 来自答案中提供的链接。 归功于 Baeldung。

    【讨论】:

    • 我在我的问题中提到了这一点 - “我知道如何注入在 myOtherProperties.properties 中声明的各个字段,但这不是我想要在这里实现的。我希望加载整个将文件放入变量 - 属性类型的 myOtherProp。”
    • 在示例 2 中,整个属性文件正在加载,对吗?您只需要属性 myProperties 吗?如果类类型属性没有库依赖,可能你可以在这里使用示例 2。
    • 在示例 2 中,它也在加载属性文件并访问其中声明的单个属性。这不是我想要达到的目标,正如我的描述中已经说明的那样,我想将整个文件加载到 util.Properties 变量中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多