Java Reference
In-Depth Information
The next listing contains another test in the test case that illustrates setting a bean's proper-
ties.
Listing 7.28. Setting bean properties in the
BeanBuilder
, from BeanBuilderTests
void testSimpleBean() {
def bb = new BeanBuilder()
bb.beans {
bean1(Bean1) {
person = "homer"
age = 45
props = [overweight:true, height:"1.8m"]
children = ["bart", "lisa"]
}
}
def ctx = bb.createApplicationContext()
assert ctx.containsBean("bean1")
def bean1 = ctx.getBean("bean1")
assertEquals "homer", bean1.person
assertEquals 45, bean1.age
assertEquals true, bean1.props?.overweight
assertEquals "1.8m", bean1.props?.height
assertEquals(["bart", "lisa"], bean1.children)
}
Inside the builder the syntax uses the bean name followed by the bean class in parentheses.
In this case,
bean1
is the name or ID of an instance of the
Bean1
class. Near the bottom
of the file you'll find the definition of
Bean1
:
class Bean1 {
String person
int age
Properties props
List children
}
In fact, several beans are defined at the bottom of the class. Unlike Java, Groovy source
filescanhavemultipleclassesdefinedinthem.The
Bean1
classcontainsattributesoftype
String
,
int
,
Properties
, and
List
. The test case assigns the
name
to
homer
and
the
age
to
45
, uses the map syntax to assign the
overweight
and
height
properties,
and sets the list to the names of the children.
[
18
]
The tests then assert that the bean is in the
application context and that, after retrieving it, all the properties have been set as described.