要求:阅读弹簧配置。 xml并尝试将spring bean解组为Java对象。
我对以下Groovy代码有一些问题:
源代码
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=
答案 0 :(得分:1)
您将属性作为地图的关键。尝试更改:
Bean beanObject = new Bean( id: bean.@id, clazz: bean.@class, parent: bean.@parent )
到
Bean beanObject = new Bean( id : bean.@id.text(),
clazz : bean.@class.text(),
parent : bean.@parent.text() )
此外,您可以通过将Bean
更改为:
@EqualsAndHashCode( includes=[ 'id' ] )
class Bean {
def id, clazz, parent,parentClazz
String toString() {
"Bean{id=$id clazz=${clazz ?: parentClazz?.clazz} parent=$parent}"
}
}
您的readXML
方法可以提炼为:
private static void readXML() {
def beans = new XmlSlurper().parse( new File("C:/Developer/beans.xml") )
def beanMap = beans.bean.inject( [:] ) { map, bean ->
Bean beanObject = new Bean( id : bean.@id.text(),
clazz : bean.@class.text(),
parent : bean.@parent.text() )
map << [ (beanObject.id): beanObject ]
beanObject.parentClazz = map[ beanObject.parent ]
map
}
}
或(甚至更短)
private static void readXML() {
def beans = new XmlSlurper().parse( new File("C:/Developer/beans.xml") )
def beanMap = beans.bean.inject( [:] ) { map, bean ->
map << [ (bean.@id.text()): new Bean( id : bean.@id.text(),
clazz : bean.@class.text(),
parent : bean.@parent.text(),
parentClazz : map[ bean.@parent.text() ] ) ]
}
}