...">

Generate Spring bean definition from Java object

Suppose I have a bean defined in Spring:

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

Then we have many clients, each of which has a slightly different configuration for its "neatBean". The old way we would have done was to have a new file for each client (for example, clientX_NeatFeature.xml) that contained a bunch of beans for this client (they were manually edited and part of the code base):

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

Now I want to have a user interface where we can edit and redefine the neatBean client on the fly.

My question is, given the neatBean and the user interface, which can "override" the properties of this bean, what would be an easy way to serialize this into an XML file, as we do [manually] today?

For example, if the user set property “17” for client Y, I would like to generate:

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

Note that moving this configuration to a different format (e.g. database, other-schema'd-xml) is an option, but is not really the answer to this question.

+3
source share
6 answers

Spring - beans 2.5 xsd xjc Java JAXB. Spring - beans ( ), XML-, JAXB Marshaller, Pablojim .

+7

, , IDE, IntelliJ Eclipse ( Spring).

bean ( ) java-, , , . Ctrl-Space, ..

, "" Java Spring, , .

+3

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. , , xml jaxb:

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

+2

, , factory .

Spring bean FactoryBean, , bean. NeatBeanFactoryBean ( xml), , , (, ) ( ).

+2

, , Spring bean (. org.springframework.beans.factory.config.BeanDefinition); .

+1

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

and then in bean def:

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

Then for each client you can have clientX.propertiescontaining

whateverValue=17
whateverAnotherValue=SomeText

.propertiesfiles are easier to edit both manually and programaticalyl using methods java.util.Properties store(..)/save(..)

+1
source

Source: https://habr.com/ru/post/1748039/


All Articles