我有大量通过JAXB (maven-jaxb2-plugin)生成的对象,并使用jaxb2-annotate-plugin对它们进行注释。这些类可以定义一个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>问题:我的注释的类型参数仍然被定义为"SomeRelationType"。如果我可以使用在@name表达式中定义的相同的XPath,那就太好了。然后,名称以"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中是可能的还是不可能的?
发布于 2016-03-19 13:35:57
但是我有大量的注释,手工定义每个注释不仅乏味,而且在更改和扩展方面也很糟糕。
对我来说,@com.example.RelationType(type = "SomeRelationType")看起来就像一种琐碎的方法,可以通过反射导出,无需任何注释。因此,请检查是否有一种方法来做“约定而不是配置”的事情。
jaxb2-annotate-plugin不支持参数化,也不支持参数化,因为它太窄,太复杂,无法实现。免责声明我是jaxb2 2-注释-插件的作者。
我认为有两种选择:
好的,只有两个选择。
https://stackoverflow.com/questions/36082277
复制相似问题