3
ClassPathXmlApplicationContext ct = new ClassPathXmlApplicationContext();

ct.refresh();
ConfigurableListableBeanFactory bf = ct.getBeanFactory();

Ad bean = (Ad) bf.createBean(Ad.class);
System.out.println("bean ="+bean);  
System.out.println("size= "+bf.getBeansOfType(Ad.class).size()); // print  0

广告类,这里是广告类信息,AD扩展了AbstractAd类:

public class Ad {

 @Override
   public String toString() {
       return "ad[adid=" + this.getId() + "]";
   }

}

这是日志:

[DEBUG] Creating instance of bean 'com.Ad'
[DEBUG] Finished creating instance of bean 'com.Ad'
bean = ad[adid=null]
size= 0

在我看来,大小应该是 1,有什么问题?

ps:最后我使用 GenericApplicationContext 和 BeanDefinition 并成功 createBean 并从上下文中获取,

   GenericApplicationContext ct = new GenericApplicationContext();

    ct.refresh();

    ConfigurableListableBeanFactory bf = ct.getBeanFactory();
    System.out.println("--------------start------------/n--------------------------/n-------------------/n");

    BeanDefinition definition = new RootBeanDefinition(Ad.class);
     ct.registerBeanDefinition("sampleService", 
    System.out.println(bf.getBeansOfType(Ad.class).size()); //print 1

日志:

[DEBUG] Creating instance of bean 'sampleService'
[DEBUG] Eagerly caching bean 'sampleService' to allow for resolving potential circular    references
[DEBUG] Finished creating instance of bean 'sampleService'
1

但我仍然想知道:为什么 getBeansOfType(Ad.class).size()在 ClassPathXmlApplicationContext creteBean 之后为 0 ?

4

1 回答 1

2

在 ClassPathXmlApplicationContext 中,您没有传递任何 XML,如果您传递任何 spring config xml,那么它将显示预期的结果。也Ad bean = (Ad) bf.createBean(Ad.class);只会创建一个类的bean。但它不会将其添加到小枝上下文中。

在第二个代码中,您使用 registerBeanDefinition 方法注册您的 bean。这样它就显示出预期的结果。

我已经尝试过以下代码并且它可以工作

ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("/Beans.xml");
        classPathXmlApplicationContext.refresh();
        ConfigurableListableBeanFactory beanFactory = classPathXmlApplicationContext.getBeanFactory();
        System.out.println(beanFactory.getBeansOfType(HelloWorld.class).size());
于 2013-03-29T07:46:59.790 回答