【问题标题】:How to pass in filename value property with today's date如何使用今天的日期传入文件名值属性
【发布时间】:2015-05-08 14:03:52
【问题描述】:
   <bean id="FileWriter" class="com.sample.FileWriter">
          <constructor-arg value="${path.to.output}"/>
          <constructor-arg value="${filename}"/>
   </bean>

我想使用 spring 从属性文件中传入带有今天日期的文件名,这样它就不会在类中进行硬编码。这可能吗?

我希望在 F_IN_1243_MMDDYYYY.xml 中传递的文件名,其中 MMDDYYYY 是今天的日期?

【问题讨论】:

  • 如何创建具有静态方法的bean,根据您的格式生成文件名,然后通过SpringEl在xml中注入bean属性

标签: java spring configuration file-properties


【解决方案1】:

您应该能够使您的 bean 原型化范围并在您的属性表达式中包含一个 java 方法调用。类似的东西:

   <bean id="FileWriter" class="com.sample.FileWriter" scope="prototype">
          <constructor-arg value="${path.to.output}"/>
          <constructor-arg value="#{T(Utils).filename()}"/>
   </bean>

Utils.filename () 是一个实用方法,它调用 SimpleDateFormat 并组成文件名。

【讨论】:

    【解决方案2】:

    有什么原因你不能在构造函数或 FileWriter 的其他方法中获取日历对象的当前日期,并使用传入的文件名作为文件前缀?

    【讨论】:

      【解决方案3】:

      您可以使用 Spring 表达式语言 (SpEL)。

      http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html

      你应该可以做这样的事情:

      <constructor-arg value="#{new SimpleDateFormat('MMddyyyy').format(new Date())}"/>
      

      使用 # 而不是 $ 并添加必要的依赖项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-21
        • 2017-10-02
        • 1970-01-01
        • 2021-09-12
        • 2022-12-24
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多