从Java对象生成Spring bean定义

时间:2010-06-01 20:14:39

标签: java spring xml-serialization

让我们建议我在Spring中定义一个bean:

<bean id="neatBean" class="com..." abstract="true">...</bean>

然后我们有很多客户端,每个客户端的'neatBean'配置略有不同。我们这样做的旧方法是为每个客户端(例如,clientX_NeatFeature.xml)创建一个新文件,其中包含一组用于此客户端的bean(这些是手工编辑的,代码库的一部分):

<bean id="clientXNeatBean" parent="neatBean">
    <property id="whatever" value="something"/>
</bean>

现在,我希望有一个UI,我们可以动态编辑和重新定义客户端的neatBean。

我的问题是:给定一个neatBean,以及一个可以“覆盖”此bean属性的UI,将这个序列化为XML文件的简单方法就像我们今天[手动]那样做?

例如,如果用户为客户端Y设置属性为“17”,我想生成:

<bean id="clientYNeatBean" parent="neatBean">
    <property id="whatever" value="17"/>
</bean>

请注意,将此配置移动到其他格式(例如,数据库,其他架构-xml)是一种选择,但不是对手头问题的真正答案。

6 个答案:

答案 0 :(得分:7)

您可以从here下载Spring-beans 2.5 xsd并在其上运行xjc以生成带有JAXB绑定的Java类。然后,您可以在运行时创建Spring-beans对象层次结构(并根据需要对其进行操作),然后使用JAXB Marshaller将其序列化为XML字符串,如Pablojim的answer所示。

答案 1 :(得分:3)

如果您想要一个简单的实现,没有工作解决方案,您可以查看IntelliJ和Eclipse(Spring Tool Suite)中提供的IDE支持。

他们解析所有bean文件(你可以配置哪个集合)并检查java代码,以便它知道哪些类,哪些属性在这些类中。在任何地方你都可以使用Ctrl-Space来帮助选择等等......

我想你可以设置没有Java代码的'项目',只设置弹簧配置文件,以减少必须进行这些更改的一线人员的学习曲线。

答案 2 :(得分:2)

我会用Jax-b来做这件事。您将创建一个bean对象,其中包含一个属性对象列表。

@XmlRootElement(name = "bean")
@XmlAccessorType(XmlAccessType.FIELD)

public class Bean {

  @XmlAttribute
  private String id;
  @XmlAttribute
  private String parent;

  @XmlElement(name="property")
  private List<BeanProperty> properties

然后您还需要向BeanProperty添加注释。然后当你有一个填充的对象时,只需使用jaxb:

将其编组为xml
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal( myBean, System.out );

有关完整的代码示例,请参阅:http://java.sun.com/webservices/docs/2.0/tutorial/doc/JAXBUsing.html

或者你可以使用Groovy - 你可以将它放到位并创建这个xml非常简单......:http://www.ibm.com/developerworks/java/library/j-pg05199/index.html

答案 3 :(得分:2)

你需要的东西显然是你的neatBeans的工厂。

在Spring中,您可以声明一个FactoryBean,而不是声明一个bean,它的作用是实际创建和配置最终的bean。 NeatBeanFactoryBean可以读取属性文件(或xml配置)以确定如何配置生成的neatBeans,具体取决于某些运行时参数(例如当前的clientID)或编译时参数(环境变量)。

答案 4 :(得分:1)

要添加其他两个问题,我相信Spring已经有了一个bean定义的工作模型(参见org.springframework.beans.factory.config.BeanDefinition);你可以将你的工作建立在那个基础上。

答案 5 :(得分:1)

我建议使用

<context:property-placeholder location="classpath*:clientX.properties"/>

然后在你的bean def:

<bean id="${clientYNeatBeanId}" parent="neatBean">
    <property id="whatever" value="${whateverValue}"/>
</bean>

然后,对于每个客户,您可以拥有clientX.properties包含

whateverValue=17
whateverAnotherValue=SomeText

.properties个文件更易于手动编辑,并通过java.util.Properties store(..) / save(..)方法进行编辑