After searching whole jaxb documentation and many tutorials, I did not find any answer that can configure dates apart from what we hard code in XMLAdapter.
I put a property file in classpath having date formats as for example:
dateFormat=mm-dd-YYYY
Now your XMLAdapter implementation goes as below:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ConfigurableAdapterForDate extends XmlAdapter<String, Date>{
private static final String FORMAT = "yyyy-mm-dd";
private String formatFromFile = null;
private SimpleDateFormat format = new SimpleDateFormat();
private void setFormatFromFile() throws IOException {
//load property file
Properties prop = new Properties();
InputStream is = this.getClass().getResourceAsStream("<path to your property file>");
prop.load(is);
//get the format from loaded property file
formatFromFile = prop.getPropertyValue("dateFormat");
if(formatFromFile != null) {
format.applyPattern(formatFromFile);
}
else {
format.applyPattern(FORMAT );
}
}
@Override
public Date unmarshal(String v) throws Exception {
this.setFormatFromFile();
return format.parse(v);
}
@Override
public String marshal(Date v) throws Exception {
this.setFormatFromFile();
return format.format(v);
}
}
Now you can use @XmlJavaTypeAdapter(ConfigurableAdapterForDate.class)for date objects which you want to serialize/deserialize.
One is free to use spring also to load property file. Above code will configure your date accordingly.