views:

258

answers:

1

Let's say I have a class Person with properties name and age, and it can be configured with Spring like so:

<beans:bean id="person" class="com.mycompany.Person">
  <beans:property name="name" value="Mike"/>
  <beans:property name="age" value="38"/>
</beans:bean>

I'd like to have a custom Spring schema element for it, which is easy to do, allowing me to have this in my Spring configuration file:

<Person name="Mike" age="38"/>

The schema definition would look something like this:

<xsd:complexType name="Person">
  <xsd:complexContent>
    <xsd:extension base="beans:identifiedType">
      <xsd:attribute name="name" type="xsd:string"/>
      <xsd:attribute name="age" type="xsd:int"/>
    </xsd:extension>
  </xsd:complexContent>
</xsd:complexType>

Based on this, let's now say I would like the option of mixing and matching my custom schema element with traditional elements and attributes of Spring beans, so I could have the option of doing this:

<Person name="Mike">
  <beans:property name="age" value="38"/>
</Person>

How would I go about doing that? Perhaps this is impossible without some major customization, but I'm hoping there is some fairly simple mechanism to achieve this. I thought extending "bean" might be the trick, but that doesn't look to be correct.

A: 

First of, if your example is really all you want to do, consider using p-namespace instead and save yourself some major headache:

<beans:bean id="person" class="com.mycompany.Person" p:name="Mike" p:age="38"/>

Yes, it doesn't look as pretty as <Person name= age= /> but there's no custom code to write :-)

If that does not satisfy your requirements, you're looking at implementing your own namespace / bean definition parser. Spring documentation has a chapter dedicated to that which will explain it better then I can. If you hit any issues, please post back specific questions and I'll try to help.

ChssPly76
Thanks. I have written my own custom bean definition parser and it was actually pretty easy. Now I'm trying to set it up so my custom bean definitions can optionally contain nested "normal" bean definition elements like in my example above. The idea is I can choose to create customizations for the most common attributes of a bean, but leave the less common ones to the traditional spring elements.
SingleShot
One issue with that approach is that you can't write your XSD easily. Extending `beans:identifiedType` does not define nested elements; they're defined within `beanElements` group which is not referenceable from outside; so you'll have to manually list `property` and whatever else you want in your XSD. Other then that, nested elements should be handled for you automatically; take a look at Spring's util namespace and its handler / parsers; the one for Map in particular.
ChssPly76
@SingleShot any updates/progress on your custom bean definition parser?
jigjig