@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"applicationContext-test.xml"}) publicclassSpringPrototypeTest{ @Autowired private BeanFactory beanFactory; @Test publicvoidtest(){ ShoppingCart cart1 = (ShoppingCart) beanFactory.getBean("shoppingCart"); assertTrue("Id of cart1 should be 9 but was "+cart1.getId(), cart1.getId() == 9); cart1.setId(100); ShoppingCart cart2 = (ShoppingCart) beanFactory.getBean("shoppingCart"); assertTrue("Id of cart2 should be 9 but was "+cart2.getId(), cart2.getId() == 9); assertTrue("Id of second cart ("+cart2.getId()+") shouldn't be the same as the first one: "+cart1.getId(), cart1.getId() != cart2.getId()); cart2.setId(cart1.getId()); assertTrue("Now (after cart2.setId(cart1.getId())), the id of second cart ("+cart2.getId()+") should be the same as the first one: " +cart1.getId(), cart1.getId() == cart2.getId()); assertTrue("Both instance shouldn't be the same", cart1 != cart2); } }
publicabstractclassAbstractApplicationContextextendsDefaultResourceLoader implementsConfigurableApplicationContext, DisposableBean{ /** Statically specified listeners */ private Set<applicationlistener<?>> applicationListeners = new LinkedHashSet<applicationlistener<?>>(); // some other fields and methods @Override publicvoidaddApplicationListener(ApplicationListener<?> listener){ if (this.applicationEventMulticaster != null) { this.applicationEventMulticaster.addApplicationListener(listener); } else {//新版本这里直接咔嚓掉,上面的applicationEventMulticaster一旦为空,就会报错的 this.applicationListeners.add(listener); } } /** * Return the list of statically specified ApplicationListeners. */ public Collection<applicationlistener<?>> getApplicationListeners() { returnthis.applicationListeners; } /** * Add beans that implement ApplicationListener as listeners. * Doesn't affect other listeners, which can be added without being beans. */ protectedvoidregisterListeners(){ // Register statically specified listeners first. for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String lisName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(lisName); } } }