JAXB:如何使用 Spring 自动生成的类?
我正在使用 xjc
从 XSD
生成 Java 类。生成的类仅包含集合类型的 getter 方法,例如 List
,但不包含 setter 方法。我如何在 Spring Framework 中使用这些生成的类作为 bean,即如何使用 applicationContext.xml 中的数据填充这些字段?
作为对“duffymo”和“fatih”的回复:实际上我可以告诉Spring使用JAXB
ObjectFactory
及其工厂方法来创建bean,
<bean id="myFactory" class="generated.ObjectFactory" />
<bean id="myBean" factory-bean="myFactory" factory-method="createMyBeanMethod" />
剩下的问题是如何在没有 setter 方法的情况下填充集合字段?
I am using xjc
to generated Java classes from an XSD
. The resulting classes only include getter methods for collection types, e.g. List
, but no setter methods. How can i use these generated classes as beans within the Spring Framework
, i.e. how to populate these fields with data from applicationContext.xml?
As a reply to 'duffymo' and 'fatih': Actually i can tell Spring to use the JAXB
ObjectFactory
and its factory methods to create the beans,
<bean id="myFactory" class="generated.ObjectFactory" />
<bean id="myBean" factory-bean="myFactory" factory-method="createMyBeanMethod" />
the remaining problem is how to populate the collection fields without having setter methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不相信你可以,因为它们是在 JAXB 的控制下创建的,而不是 Spring bean 工厂。
I don't believe you can, because they were created under JAXB's control and not the Spring bean factory.
您可以使用字段代替 getter/setter。
You can use the field instead of the getter/setter.
由于生成的代码处于 JAXB 的控制之下,因此您将无法执行此操作。然而,可能有一个解决方法:
假设 JAXB 为您创建一个 Person 类,生成的属性将受到保护。
您可以创建扩展 Person 类的新类 MyPerson,并将 setter 方法放置在 MyPerson 类中。因此,您可以从 bean 配置文件初始化该属性,并且生成的代码不会覆盖您的更改。它可能是也可能不是适合您的情况的解决方法,因为我不知道详细信息。
As the generated code is under JAXB's control you wont be able to do that. However, a workaround maybe:
Say JAXB creates a Person class for you, generated properties will be protected.
You can create new class MyPerson extending the Person class and place the setter method inside of MyPerson class. So you can init the property from bean config file and the generated code wont override your changes. It may or may not be a suitable workaround for your case as I dont know the details.
有一个扩展可以为列表生成设置方法,如下所示:
尽管给定的链接似乎是由于引用的站点已被重新组织而损坏。
值得向 java.net 发布一个问题以获取集合设置器注入器的位置。
There is an extension to generate set methods for lists as indicated here:
Although the given link appears to be broken as the referenced site has been re-organized.
It would be worth posting a question to java.net to get the location of the collection-setter-injector.
您可以使用 这些 bean 的基于 Java 的配置。
Instead of populate your
xjc-generated
beans in applicationContext.xml, you can use Java-based configuration for those beans.