Anyway to pass a constructor parameter to a JAXB Adapter?

前端 未结 2 759
一生所求
一生所求 2021-02-20 08:45

I\'m using Spring 3 IOC and JAXB/JAX-WS in a WebService that I wrote. I am having a slight issue right now with data that must be rounded prior to returning to the consumer as

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 09:11

    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 {
    
        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 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);
        }
    }
    

提交回复
热议问题