使用ClassPathXmlApplicationContext以编程方式创建Bean但无法获取bean;弹簧

时间:2013-03-28 12:48:18

标签: java spring

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并获取了From context,

   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

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

1 个答案:

答案 0 :(得分:2)

在ClassPathXmlApplicationContext中

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

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

我尝试过以下代码并且可以正常工作

ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("/Beans.xml");
        classPathXmlApplicationContext.refresh();
        ConfigurableListableBeanFactory beanFactory = classPathXmlApplicationContext.getBeanFactory();
        System.out.println(beanFactory.getBeansOfType(HelloWorld.class).size());