要求:阅读弹簧配置。xml 并尝试将 spring bean 解组为 Java 对象。
我对以下 Groovy 代码有一些问题:
- println("found >> "+beanMap[beanObject.parent]) 这并没有像我预期的那样返回 bean 类。更奇怪的是,接下来的 2 行输出。
- 我希望 toString() 的输出看起来像,如果 clazz 为空,它应该打印 parentClazz,但显然不是。为什么会这样?
源代码
class TestGroovy {
public static void main(String[] args) throws FileNotFoundException {
readXML();
}
private static void readXML() {
//def beans = new XmlSlurper().parse(new File("C:/Developer/interest-ratecollector-system.xml"))
def beans = new XmlSlurper().parse(new File("C:/Developer/beans.xml"))
def beanMap = [:];
//println beans.bean.size()
for (bean in beans.bean.list()) {
//print("id=" + bean.@id + ",clazz=" + bean.@class + ",parent = " + bean.@parent)
Bean beanObject = new Bean(id: bean.@id, clazz: bean.@class, parent: bean.@parent)
beanMap[beanObject.id] = beanObject;
//println("map>"+beanMap)
if (beanMap.size()>1)
beanMap.each{element ->
println "elem="+(element.key==beanObject.parent)
println(beanMap[element.key])
println(beanMap[beanObject.parent])
}
beanObject.parentClazz = beanMap[beanObject.parent]
println("found >> "+beanMap[beanObject.parent])
println("\nbeanObject="+beanObject)
println()
}
}
}
@ToString(includeNames=true)
class Bean {
def id, clazz, parent,parentClazz
@Override
public String toString() {
return "Bean{" +
"id=" + id +
",clazz=" + clazz?:parentClazz +
", parent=" + parent +
"parentClazz=" + parentClazz +
'}';
}
boolean equals(o) {
if (this.is(o)) return true
if (getClass() != o.class) return false
Bean bean = (Bean) o
if (id != bean.id) return false
return true
}
int hashCode() {
return id.hashCode()
}
}
XML
<beans>
<bean id="class1" class="com.Class" abstract="true" init-method="init">
</bean>
<bean id="SHRED" parent="class1" abstract="true">
<property name="serviceName">
<value>SSS</value>
</property>
</bean>
</beans>
输出
found >> null
beanObject=Bean{id=class1,clazz=com.Class
elem=true
Bean{id=class1,clazz=com.Class
null
elem=false
Bean{id=SHRED,clazz=
null
found >> null
beanObject=Bean{id=SHRED,clazz=