Creating beans

Creating beans in JBG is done by configuring an XML file and running the JBG.

Write the configuration file

Create a file named tutorial-beans.xml in the /src/main/gen-config directory and set up the following root element:

<?xml version="1.0" encoding="UTF-8"?>
<jbg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jbg.sf.net/jbg"
        xsi:schemaLocation="http://jbg.sf.net/jbg http://jbg.sf.net/xsd/1.0/jbg.xsd">
</jbg>

This will enable your XML editor to pop up the XML elements automatically as you type. Note the JBG version number in the schema location URL (i.e. 1.0). You can browse the JBG web site at http://jbg.sf.net/xsd/ to see the XSD versions available and choose the one appropriate for the JBG version you are using.

Using the automatic suggestion of the editor (Ctrl+space in Eclipse), create your first bean definition as follows:

<jbg ...>
 <beans>
  <bean class="jbg.tutorial.Person">
   <property name="surname">
    <simple-type type="string" />
   </property>
   <property name="givenNames">
    <simple-type type="string" />
   </property>
   <property name="birthDate">
    <simple-type type="calendar" />
   </property>
  </bean>
 </beans>
</jbg>

This defines a JavaBean named Person in the jbg.tutorial package with 3 properties: surname, givenNames (both of type String) and birthDate of type date.

Generate Java source file

Once you build your application (e.g. mvn install), you get the Java source file of the Person bean generated.

It has the 3 properties defined, a default no-arg constructor and a full constructor, the getters and setters, and hashCode(), equals() and toString() implementations. The code is well-factored, consistent, nicely formatted and has default JavaDoc comments.

The bean is ready to be used, no fuss in coding the mundane methods by hand.

More importantly, it is easy to change the definition of the bean, by say adding a new property or renaming an existing one, and be sure that after the Java source is re-generated automatically during the build, the code is still consistent. No more worry that a new property has been forgotten to be added to equals() or to toString(), it is all done automatically by the generation.

See the Java source file generated: Person.java

Generate HTML documentation (report)

You also get an HTML documentation of the bean configuration generated within the project site. After running mvn site, a report is generated at target/site/jbg/tutorial-beans.html.

Next >>