在spring应用程序中,我想在运行时获取给定bean的对象图结构以及依赖项列表(包括嵌套)。
E.g:
public class College {
private List<Student>
private List<Staff>
private List<Department>
setter Methods....
}
public class Student {
private List<Subject>;
private Address;
setter Methods....
}
假设:
*全部注入&amp;通过弹簧连接。
*想在春天利用任何API(因此避免反思)
目标:
*通过UI向用户显示依赖关系信息。实现这一目标的其他方法是在应用程序之外维护一个副本(如db,非spring bean xml),这个副本当然很糟糕,因而避免了
答案 0 :(得分:3)
您可以使用ReaderEventListener
在上下文启动时构建对象grahp。
例如:
public class TrackingReaderEventListener extends EmptyReaderEventListener {
private Map<String, ComponentDefinition> components = new HashMap<String, ComponentDefinition>();
@Override
public void componentRegistered(ComponentDefinition componentDefinition) {
components.put(componentDefinition.getName(), componentDefinition);
}
public Map<String, ComponentDefinition> getComponentMap() {
return components;
}
public static void main (String[] args) {
TrackingReaderEventListener listener = new TrackingReaderEventListener();
ClassPathXmlApplicationContext context = new AppContext("applicationContext.xml", listener);
context.refresh(); // or may be load beans definitions only
}
}
class AppContext extends ClassPathXmlApplicationContext {
private ReaderEventListener readerListener;
public AppContext(String configLocation, ReaderEventListener readerListener) {
super(new String[] {configLocation} , false);
this.readerListener = readerListener;
}
@Override
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
super.initBeanDefinitionReader(reader);
reader.setEventListener(readerListener);
}
}
或直接从BeanFactory
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
String[] beanNames = beanFactory.getBeanDefinitionNames();
for (String beanName : beanNames) {
BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
PropertyValues pvs = bd.getPropertyValues();
String[] dependsOn = bd.getDependsOn();
...
}