简体   繁体   中英

JAXB: How to use auto-generated classes from Spring?

I am using xjc to generated Java classes from an XSD . The resulting classes only include getter methods for collection types, eg List , but no setter methods. How can i use these generated classes as beans within the Spring Framework , ie 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?

可以在这些bean中使用基于Java的配置 ,而不是在applicationContext.xml中填充xjc-generated bean。

我不相信您可以,因为它们是在JAXB的控制下创建的,而不是在Spring bean工厂的控制下创建的。

您可以使用该字段而不是getter / setter。

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.

     generated :
     public class Person{
          protected List<Something> somethingList;
          .
          .
     }




     class MyPerson extends Person{
         public void setList(List<Something> somethingList){
             this.somethingList= somethingList;
         }

     }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM