[英]XML & JAXB: pass attribute into value
我有大量通過JAXB( maven-jaxb2-plugin
)生成的對象,並使用jaxb2-annotate-plugin
。 這些類可以定義一個RelationType
,我想用相應的@RelationType
注釋@RelationType
注釋。 我使用XPath表達式在XSD中找到name屬性並注釋該類,並將其特定類型傳遞到注釋中。 下面是一個示例:
<jaxb:bindings node="//xsd:complexType[@name='SomeRelationType']">
<annox:annotate target="class">@com.example.RelationType(type = "SomeRelationType")</annox:annotate>
</jaxb:bindings>
對應以下XSD代碼段:
<xsd:complexType name="SomeRelationType">
<xsd:complexContent>
<xsd:extension base="RelationType">
<xsd:sequence>
<xsd:element name="someValue" type="SomeValue"/>
<xsd:element name="otherValue" type="OtherValue"/>
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
我找到了在的ComplexType SomeRelationType
的名稱,並注釋類@RelationType
注解,它具有SomeRelationType
作為其類型參數。 它將生成以下類:
@RelationType(type = "SomeRelationType")
public class SomeRelationType extends RelationType implements Serializable {
private final static long serialVersionUID = 1L;
protected SomeValue someValue;
protected OtherValue otherValue;
}
如果它只是幾個域對象,則效果很好。 但是我的工作量很大,手動定義每個注釋不僅繁瑣,而且在更改和擴展方面也很糟糕。
為了泛化它,我可以將XPath表達式重寫為以下內容:
<jaxb:bindings node="//xsd:complexType[substring(@name, string-length(@name) - string-length('RelationType') + 1)]" multiple="true">
<annox:annotate target="class">@com.example.RelationType(type = "SomeRelationType")</annox:annotate>
</jaxb:bindings>
問題:我的注釋的type參數仍然定義為"SomeRelationType"
。 如果我可以使用XPath表達式中定義的@name
,那將是很好的。 然后,所有名稱以"RelationType"
結尾的類也將自動獲取帶有正確type
參數的@RelationType
批注。
當然,它不像執行以下操作那樣簡單,但是它顯示了我想要實現的目標:
<jaxb:bindings node="//xsd:complexType[substring(@name, string-length(@name) - string-length('RelationType') + 1)]" multiple="true">
<annox:annotate target="class">@com.example.RelationType(type = @name)</annox:annotate>
</jaxb:bindings>
這樣的事情在XML / JAXB中甚至可能嗎?
但是我的工作量很大,手動定義每個注釋不僅繁瑣,而且在更改和擴展方面也很糟糕。
對我來說, @com.example.RelationType(type = "SomeRelationType")
看起來像一個簡單的元信息,可以通過反射來導出而無需任何注釋。 因此,請檢查是否有一種方法可以進行“配置之上的約定”。
jaxb2-annotate-plugin
不也將不支持參數化,它實現起來太狹窄也太復雜。 免責聲明我是jaxb2-annotate-plugin的作者 。
我看到兩個選擇:
是的,只有兩個選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.