我正在编写一个程序,其中我想输出到一个文件,该文件具有yyy/MM/dd
格式的当前数据附加到文件名。
我想使用Spring将表示输出文件位置的File
对象注入到需要它的类中。
然而,我不知道如何在创建File
对象时将当前日期附加到文件名参数。
在实际代码中很容易:
String outputFileName = "someFile";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
outputFileName += " " + sdf.format(new Date());
File outputFile = new File(outputFileName);
我如何在我的Spring bean配置文件中做到这一点?
有可能这样做吗?如果有可能,我该怎么做?
嗯…从技术上讲,你几乎可以做任何事情。我使用FastDateFormat
是因为它既快(duh!)又线程安全。java.text.SimpleDateFormat
也可以使用:
<bean id="fastDateFormat" class="org.apache.commons.lang.time.FastDateFormat" factory-method="getInstance">
<constructor-arg value="yyyy/MM/dd"/>
</bean>
<bean id="currentDate" class="java.util.Date" factory-bean="fastDateFormat" factory-method="format">
<constructor-arg>
<bean class="java.util.Date"/>
</constructor-arg>
</bean>
然后直接注入:
@Resource
private String currentDate; //2011/12/13
请注意,在纯Java中运行它或使用@Configuration
方法会简单得多:
@Bean FastDateFormat fastDateFormat() {
return new FastDateFormat("yyyy/MM/dd");
}
@Bean String currentDate() = {
return fastDateFormat().format(new Date());
}
话虽这么说,为什么不直接在@PostConstruct
中编写纯Java而不是过度依赖DI呢?不是所有的东西都要注射……唯一的好处是,它使测试更容易,因为您可以注入假字符串,而不依赖于当前日期。但在这种情况下,考虑一些DateProvider
接口,使生活更简单。
你真的想在整个应用程序生命周期中都有相同的日期吗(它将在启动时生成)?如果没有,currentDate
bean必须具有prototype
作用域,并且每次需要时必须从容器中惰性地获取它。