java – jaxb可以解析系统属性吗?
作者:互联网
我们使用JAXB来配置XML对象.我想知道JAXB是否有办法解析系统属性.例如,如果我有一个属性颜色的bean,我希望能够这样做:
<mybean color="${mycolor.in.data.property}" />
但是如果我这样做,JAXB创建mybean对象,颜色将等于字符串:
mycolor.in.data.property
JAXB在春天是否有相应的PropertyPlaceholderConfigurer,以便我的系统属性可以解决?
解决方法:
XmlAdapter是一种JAXB (JSR-222)机制,允许您在编组/解组时将对象转换为另一个对象.您可以编写一个XmlAdapter,将系统属性名称转换为实际值.
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ColorAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) throws Exception {
return System.getProperty(v);
}
@Override
public String marshal(String v) throws Exception {
return v;
}
}
然后使用@XmlJavaTypeAdapter批注为您的属性配置XmlAdapter.
@XmlJavaTypeAdapter(ColorAdapter.class)
public String getColor() {
return color;
}
欲获得更多信息
> http://blog.bdoughan.com/2011/05/jaxb-and-joda-time-dates-and-times.html
UPDATE
Ok thanks. Actually I do not have access to the class, as this is part
of an imported library. So I was more looking of a way to configure
this directly in the xml file, but it is probably not possible.
如果无法修改类,则可以使用StreamReaderDelegate修改XML输入.有一些方法可以处理文本/字符数据,因此您可能需要进行实验以确保覆盖最适合您正在使用的JAXB实现的方法.
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyBean.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource source = new StreamSource("input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(source);
xsr = new StreamReaderDelegate(xsr) {
@Override
public String getText() {
String text = super.getText();
if(text.contains("${")) {
text = System.getProperty(text);
}
return text;
}
};
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.unmarshal(xsr);
}
}
标签:java,properties,xml,jaxb,unmarshalling 来源: https://codeday.me/bug/20190629/1329307.html