Anyway to pass a constructor parameter to a JAXB Adapter?

社会主义新天地 提交于 2019-12-04 02:19:44

I'm not sure how you hook this in with Spring, but below is a description of the JAXB mechanism that you can leverage.

If you have the following:

@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(value=RoundingAdapter.class,type=java.math.BigDecimal.class)

Then using the standalone JAXB APIs you could do the following. The code below means whenever the RoundingAdapter is encountered, the specified instance should be used.

marshaller.setAdapter(new RoundingAdapter(4));
unmarshaller.setAdapter(new RoundingAdapter(4));

For More Information

Usage

import com.company.BigDecimalAdapter.X$XXXX;
...

@XmlElement(name = "QTY")
@XmlJavaTypeAdapter(X$XXXX.class)
private BigDecimal quantity;

BigDecimalAdapter

import static java.math.RoundingMode.HALF_UP;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class BigDecimalAdapter extends XmlAdapter<String, BigDecimal> {

    public static final class X$XX extends BigDecimalAdapter {
        public X$XX() {
            super("#.##");
        }
    }

    public static final class X$00 extends BigDecimalAdapter {
        public X$00() {
            super("#.00");
        }
    }

    public static final class X$XXXX extends BigDecimalAdapter {
        public X$XXXX() {
            super("#.####");
        }
    }

    private final ThreadLocal<DecimalFormat> format;

    public BigDecimalAdapter(String pattern) {
        format = ThreadLocal.withInitial(() -> {
            DecimalFormat df = new DecimalFormat(pattern);
            df.setRoundingMode(HALF_UP);
            return df;
        });
    }

    @Override
    public String marshal(BigDecimal v) throws Exception {
        return format.get().format(v);
    }

    @Override
    public BigDecimal unmarshal(String v) throws Exception {
        return new BigDecimal(v);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!