I’m working on a program where I want to output to a file that has the current data in yyy/MM/dd format appended to the filename.
I want to inject the File object representing the output file location into the class that needs it using Spring.
However, I don’t know how to append the current date to the filename argument when creating the File object.
In actual code it’s easy:
String outputFileName = "someFile";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
outputFileName += " " + sdf.format(new Date());
File outputFile = new File(outputFileName);
How can I do this in my Spring bean configuration file?
Is it even possible to do this, and if so how could I go about it?
Well… technically you can do almost everything. I’m using
FastDateFormatbecause it’s both fast (duh!) and thread-safe.java.text.SimpleDateFormatcan be used as well:And then simply inject:
Note that it would be much simpler to run it in plain Java or using
@Configurationapproach:That being said, why don’t you just write it plain Java in
@PostConstructrather than over-relying on DI? Not everything has to be injected… The only advantage is that it makes testing easier since you can inject fake string and do not rely on current date. But in this case think of someDateProviderinterface, makes life simpler.Also do you really want to have the same date for the whole application lifetime (it will be generated once at startup)? If not,
currentDatebean must haveprototypescope and you must lazily fetch it from the container every time you need it…