BeanFactory的对象注册与依赖绑定方式

public static void main(String[] args)
{
  DefaultListableBeanFactory beanRegistry=new DefaultListableBeanFactory();
  BeanFactory container=(BeanFactory)bindViaCode(beanRegistry);
  
  FXNewsProvider newsProvider=(FXNewsProvider)container.getBean("djNewsProvider");
  newsProvider.getAndPersistNews(); 
}

public static BeanFactory bindViaCode(BeanDefinitionRegistry registry)
{
  AbstractBeanDefinition newsProvider=new RootBeanDefinition(FXNewsProvider.class,true);
  AbstractBeanDefinition newsListener=new RootBeanDefinition(DowJonesNewsListener.class,true);
  AbstractBeanDefinition newsPersister=new RootBeanDefinition(DowJonesNewsPersister.class,true);

  //将bean定义注册到容器中
  registry.registerBeanDefinition("djNewsProvider",newsProvider);
  registry.registerBeanDefinition("djNewsListener",newsListener);
  registry.registerBeanDefinition("djNewsPersister",newsPersister);
  
  //指定依赖关系
   
  //1.可以通过构造方法注入方式
  ConstructorArgumentValues argValues=new ConstructorArgumentValues();
  argValues.addIndexedArgumentValue(0,newsListener);
  argValues.addIndexedArgumentValue(1,newsPersister);
  newsProvider.setConstructorArgumentValues(argValues);
  
  //2.或者通过setter方法注入方式
  MutablePropertyValues propertyValues=new MutablePropertyValues();
  propertyValues.addPropertyValue(new PropertyValue("newsListener",newsListener));
  propertyValues.addPropertyValue(new PropertyValue("newsPersister",newsPersister));
  newsProvider.setPropertyValues(propertyValues);
  
  //绑定完成
  return (BeanFactory)registry;
  
}

 

posted @ 2012-06-26 14:13  来自非洲大草原的食人虎  阅读(395)  评论(0编辑  收藏  举报