Java Reference
In-Depth Information
void testImportSpringXml() {
def bb = new BeanBuilder()
bb.beans {
importBeans "classpath:grails/spring/test.xml"
}
def ctx = bb.createApplicationContext()
def foo = ctx.getBean("foo")
assertEquals
"hello", foo
}
}
To use
BeanBuilder
all you have to do is instantiate the class. This is similar to using
MarkupBuilder
,
SwingBuilder
,
AntBuilder
, or any of the wide range of build-
ers written in Groovy. Here the builder is assigned to the variable
bb
, so using the builder
starts with
bb.beans
, which is like creating a root
<beans>
element in a Spring con-
figuration file. The curly braces then indicate child elements. Here the child element is an
importBeans
element, which reads the file test.xml from the classpath. Before proceed-
ing, here's the text of test.xml:
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<beans xmlns=
"http://www.springframework.org/schema/beans"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
>
<bean id=
"foo"
class=
"java.lang.String"
>
<constructor-arg value=
"hello"
/>
</bean>
</beans>
This is a typical beans configuration file containing a single bean definition. The bean is an
instance of
java.lang.String
whose value is
hello
and whose name is
foo
.
Returning to the test case, after importing the XML file the
createApplicationCon-
text
method isinvoked,whichmakes thebeansavailable throughtheapplication context.
Then the test calls
getBean
to return the
foo
bean and checks that its value is
hello
.
The conclusions to be drawn are that to use the
BeanBuilder
you must (1) instantiate
the class, (2) define the beans using normal builder syntax, (3) create the application con-
text from the builder, and (4) access and use the beans in the normal way.