public static MangoConfig getMangoConfig(DefaultListableBeanFactory beanFactory,String prefix){ MangoConfig target = new MangoConfig(); PropertiesConfigurationFactory<Object> factory = new PropertiesConfigurationFactory<Object>(target); factory.setPropertySources(deducePropertySources(beanFactory)); factory.setConversionService(new DefaultConversionService()); factory.setIgnoreInvalidFields(false); factory.setIgnoreUnknownFields(true); factory.setIgnoreNestedProperties(false); factory.setTargetName(prefix); try { factory.bindPropertiesToTarget(); } catch (Exception ex) { throw new MangoAutoConfigException(ex); } return target; }
@Before public void setUp() throws Exception { final ProtectionDomain empty = new ProtectionDomain(null, new Permissions()); provider = new SecurityContextProvider() { private final AccessControlContext acc = new AccessControlContext( new ProtectionDomain[] { empty }); @Override public AccessControlContext getAccessControlContext() { return acc; } }; DefaultResourceLoader drl = new DefaultResourceLoader(); Resource config = drl .getResource("/org/springframework/beans/factory/support/security/callbacks.xml"); beanFactory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(config); beanFactory.setSecurityContextProvider(provider); }
/** * If the bean factory is a DefaultListableBeanFactory then it can serialize scoped * beans and deserialize them in another context (even in another JVM), as long as the * ids of the bean factories match. This method sets up the serialization id to be * either the id provided to the scope instance, or if that is null, a hash of all the * bean names. * * @param beanFactory the bean factory to configure */ private void setSerializationId(ConfigurableListableBeanFactory beanFactory) { if (beanFactory instanceof DefaultListableBeanFactory) { String id = this.id; if (id == null) { List<String> list = new ArrayList<>( Arrays.asList(beanFactory.getBeanDefinitionNames())); Collections.sort(list); String names = list.toString(); logger.debug("Generating bean factory id from names: " + names); id = UUID.nameUUIDFromBytes(names.getBytes()).toString(); } logger.info("BeanFactory id=" + id); ((DefaultListableBeanFactory) beanFactory).setSerializationId(id); } else { logger.warn("BeanFactory was not a DefaultListableBeanFactory, so RefreshScope beans " + "cannot be serialized reliably and passed to a remote JVM."); } }
public static <T> T instantiateComponent(DefaultListableBeanFactory beanFactory, Class<T> cls, Annotation annotation) { T extractor; try { extractor = beanFactory.getBean(cls); } catch (BeansException e) { try { extractor = (T) beanFactory.getBean(cls.getName()); } catch (BeansException e1) { BeanDefinitionBuilder beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(cls.getName()); beanFactory.registerBeanDefinition(cls.getName(), beanDefinition.getBeanDefinition()); extractor = (T) beanFactory.getBean(cls.getName()); } } return extractor; }
/** * Loads the bean definitions via an XmlBeanDefinitionReader. * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }
/** * Loads the bean definitions via an XmlBeanDefinitionReader. * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }
/** * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle. */ @Override protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
/** * Build an internal BeanFactory for resolving target beans. * @param containingFactory the containing BeanFactory that originally defines the beans * @return an independent internal BeanFactory to hold copies of some target beans */ protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) { // Set parent so that references (up container hierarchies) are correctly resolved. DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory); // Required so that all BeanPostProcessors, Scopes, etc become available. internalBeanFactory.copyConfigurationFrom(containingFactory); // Filter out BeanPostProcessors that are part of the AOP infrastructure, // since those are only meant to apply to beans defined in the original factory. for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) { if (it.next() instanceof AopInfrastructureBean) { it.remove(); } } return internalBeanFactory; }
/** * Provides a static, single instance of the application context. This method can be * called repeatedly. * <p/> * If the configuration requested differs from one used previously, then the previously-created * context is shut down. * * @return Returns an application context for the given configuration */ public synchronized static ConfigurableApplicationContext getApplicationContext(ServletContext servletContext, String[] configLocations) { AbstractApplicationContext ctx = (AbstractApplicationContext)BaseApplicationContextHelper.getApplicationContext(configLocations); CmisServiceFactory factory = (CmisServiceFactory)ctx.getBean("CMISServiceFactory"); DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory(ctx.getBeanFactory()); GenericWebApplicationContext gwac = new GenericWebApplicationContext(dlbf); servletContext.setAttribute(GenericWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, gwac); servletContext.setAttribute(CmisRepositoryContextListener.SERVICES_FACTORY, factory); gwac.setServletContext(servletContext); gwac.refresh(); return gwac; }
/** * * @param acf * @param sch * @return */ private Trigger registerSchedulerTriggerBean(DefaultListableBeanFactory acf, AbstractJob sch) { //注册JobDetail String jobDetailBeanName = sch.getJobName() + "JobDetail"; if (context.containsBean(jobDetailBeanName)) { throw new RuntimeException("duplicate jobName[" + sch.getJobName() + "] defined!!"); } BeanDefinitionBuilder beanDefBuilder = BeanDefinitionBuilder .genericBeanDefinition(MethodInvokingJobDetailFactoryBean.class); beanDefBuilder.addPropertyValue("targetObject", sch); beanDefBuilder.addPropertyValue("targetMethod", "execute"); beanDefBuilder.addPropertyValue("concurrent", false); acf.registerBeanDefinition(jobDetailBeanName, beanDefBuilder.getRawBeanDefinition()); //注册Trigger String triggerBeanName = sch.getJobName() + "Trigger"; beanDefBuilder = BeanDefinitionBuilder.genericBeanDefinition(CronTriggerFactoryBean.class); beanDefBuilder.addPropertyReference("jobDetail", jobDetailBeanName); beanDefBuilder.addPropertyValue("cronExpression", sch.getCronExpr()); beanDefBuilder.addPropertyValue("group", groupName); acf.registerBeanDefinition(triggerBeanName, beanDefBuilder.getRawBeanDefinition()); logger.info("register scheduler task [{}] ok!!", sch.getJobName()); return (Trigger) context.getBean(triggerBeanName); }
public static BeanFactory makeMethodTrigger ( Object o, String method ) throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); RootBeanDefinition caller = new RootBeanDefinition(); caller.setFactoryBeanName("obj"); caller.setFactoryMethodName(method); Reflections.setFieldValue(caller.getMethodOverrides(), "overrides", new HashSet<>()); bf.registerBeanDefinition("caller", caller); Reflections.getField(DefaultListableBeanFactory.class, "beanClassLoader").set(bf, null); Reflections.getField(DefaultListableBeanFactory.class, "alreadyCreated").set(bf, new HashSet<>()); Reflections.getField(DefaultListableBeanFactory.class, "singletonsCurrentlyInCreation").set(bf, new HashSet<>()); Reflections.getField(DefaultListableBeanFactory.class, "inCreationCheckExclusions").set(bf, new HashSet<>()); Reflections.getField(DefaultListableBeanFactory.class, "logger").set(bf, new NoOpLog()); Reflections.getField(DefaultListableBeanFactory.class, "prototypesCurrentlyInCreation").set(bf, new ThreadLocal<>()); @SuppressWarnings ( "unchecked" ) Map<String, Object> objs = (Map<String, Object>) Reflections.getFieldValue(bf, "singletonObjects"); objs.put("obj", o); return bf; }
public static ApplicationContext buildAppContext(ApplicationContext parent, Stream<TestBean> beans, Collection<BeanFactoryPostProcessor> postProcessors) { final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final GenericApplicationContext applicationContext = new GenericApplicationContext(beanFactory, parent); postProcessors.forEach(applicationContext::addBeanFactoryPostProcessor); beans.forEach(entry -> { final String factoryBean = entry.getName() + "_factory"; beanFactory.registerSingleton(factoryBean, (Supplier<Object>) entry::getBean); beanFactory.registerBeanDefinition(entry.getName(), BeanDefinitionBuilder .rootBeanDefinition(entry.getBean() != null ? entry.getBean().getClass() : Object.class) .setFactoryMethodOnBean("get", factoryBean) .getBeanDefinition()); }); applicationContext.refresh(); return applicationContext; }
@Test public void should_register_mock_definitions_when_destination_bean_does_not_exists() { //given final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( singleton(mockDefinition.getName()), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(mockDefinition.getName())); }
@Test public void should_replace_bean_definition_with_mock_definition_when_destination_bean_exists_match_by_name() { //given final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerBeanDefinition(mockDefinition.getName(), beanDefinition(Service.class)); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( singleton(mockDefinition.getName()), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(mockDefinition.getName())); }
@Test public void should_replace_bean_definition_with_mock_definition_when_destination_bean_exists_in_parent_bean_factory_match_by_name() { //given final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final DefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory(); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parentFactory); parentFactory.registerBeanDefinition(mockDefinition.getName(), beanDefinition(Service.class)); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( singleton(mockDefinition.getName()), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(mockDefinition.getName())); }
@Test public void should_replace_bean_definition_with_mock_definition_when_single_destination_bean_exists_match_by_class() { //given final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final String beanDefinitionName = "not " + mockDefinition.getName(); beanFactory.registerBeanDefinition(beanDefinitionName, beanDefinition(Service.class)); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( singleton(beanDefinitionName), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(beanDefinitionName)); }
@Test public void should_replace_bean_definition_with_mock_definition_when_single_destination_bean_exists_in_parent_bean_factory_match_by_class() { //given final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final String beanDefinitionName = "not" + mockDefinition.getName(); final DefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory(); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parentFactory); parentFactory.registerBeanDefinition(beanDefinitionName, beanDefinition(Service.class)); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( singleton(beanDefinitionName), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(beanDefinitionName)); }
@Test public void should_register_mock_as_yet_another_bean_when_multiple_definition_exists() { //given final DefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory(); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parentFactory); final DoubleDefinition mockDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final String parentBeanDefinitionName = "parent not " + mockDefinition.getName(); final String beanDefinitionName = "not " + mockDefinition.getName(); parentFactory.registerBeanDefinition(parentBeanDefinitionName, beanDefinition(Service.class)); beanFactory.registerBeanDefinition(beanDefinitionName, beanDefinition(Service.class)); //when new DoubleContextBuilder() .withMock(mockDefinition) .doProcess(beanFactory); //then assertEquals( asSet(parentBeanDefinitionName, beanDefinitionName, mockDefinition.getName()), allDefinitionNames(beanFactory)); assertMockWillBeCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(mockDefinition.getName())); }
@Test public void should_register_spy_definition_when_destination_bean_does_not_exists() { //given final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition spyDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); //when new DoubleContextBuilder() .withSpy(spyDefinition) .doProcess(beanFactory); //then assertEquals( singleton(spyDefinition.getName()), allDefinitionNames(beanFactory)); assertSpyIsCreatedByDoubleFactory(beanFactory.getMergedBeanDefinition(spyDefinition.getName())); }
@Test public void should_do_nothing_with_existing_bean_when_spy_creation_requested() { //given final DoubleDefinitionsRegistrationContext registrationContext = new DoubleDefinitionsRegistrationContext(); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition spyDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final String definitionName = "not " + spyDefinition.getName(); beanFactory.registerBeanDefinition(definitionName, beanDefinition(Service.class)); //when new DoubleContextBuilder() .withSpy(spyDefinition) .withRegistrationContext(registrationContext) .doProcess(beanFactory); //then assertEquals( singleton(definitionName), allDefinitionNames(beanFactory)); assertFalse(registrationContext.isBeanDefinitionRegisteredForDouble(spyDefinition)); }
@Test public void should_do_nothing_with_existing_bean_in_parent_bean_factory_when_spy_creation_requested() { //given final DoubleDefinitionsRegistrationContext registrationContext = new DoubleDefinitionsRegistrationContext(); final DefaultListableBeanFactory parentFactory = new DefaultListableBeanFactory(); final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(parentFactory); final DoubleDefinition spyDefinition = DoubleDefinitionTestFactory.doubleDefinition(Service.class); final String definitionName = "not " + spyDefinition.getName(); parentFactory.registerBeanDefinition(definitionName, beanDefinition(Service.class)); //when new DoubleContextBuilder() .withSpy(spyDefinition) .withRegistrationContext(registrationContext) .doProcess(beanFactory); //then assertEquals( singleton(definitionName), allDefinitionNames(beanFactory)); assertFalse(registrationContext.isBeanDefinitionRegisteredForDouble(spyDefinition)); }
@Test public void should_register_mock_creation() { //final final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition mockDefinition = DoubleDefinition.builder() .name("mock") .doubleClass(Object.class) .build(); //when registrationContext.registerMock(beanFactory, mockDefinition); bootstrapApplicationContext(beanFactory); //then Mockito .verify(doubleFactory) .createMock(mockDefinition); }
@Test public void should_register_spy_creation() { //final final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition spyDefinition = DoubleDefinition.builder() .name("spy") .doubleClass(Object.class) .build(); //when registrationContext.registerSpy(beanFactory, spyDefinition); bootstrapApplicationContext(beanFactory); //then Mockito .verify(doubleFactory) .createSpy(null, spyDefinition); }
@Test public void should_detect_already_registered_double() { //final final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); final DoubleDefinition otherDouble = DoubleDefinition.builder() .name("other double") .doubleClass(Object.class) .build(); final DoubleDefinition spyDefinition = DoubleDefinition.builder() .name("spy") .doubleClass(Object.class) .build(); final DoubleDefinition mockDefinition = DoubleDefinition.builder() .name("mock") .doubleClass(Object.class) .build(); registrationContext.registerSpy(beanFactory, spyDefinition); registrationContext.registerMock(beanFactory, mockDefinition); bootstrapApplicationContext(beanFactory); //expect assertFalse(registrationContext.isBeanDefinitionRegisteredForDouble(otherDouble)); assertTrue(registrationContext.isBeanDefinitionRegisteredForDouble(spyDefinition)); assertTrue(registrationContext.isBeanDefinitionRegisteredForDouble(mockDefinition)); }
@Test @SuppressWarnings("serial") public void ignoredNestedUnresolvablePlaceholder() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("testBean", genericBeanDefinition(TestBean.class) .addPropertyValue("name", "${my.name}") .getBeanDefinition()); PropertySourcesPlaceholderConfigurer pc = new PropertySourcesPlaceholderConfigurer(); pc.setProperties(new Properties() {{ put("my.name", "${bogus}"); }}); pc.setIgnoreUnresolvablePlaceholders(true); pc.postProcessBeanFactory(bf); assertThat(bf.getBean(TestBean.class).getName(), equalTo("${bogus}")); }
@Test public void testPropertyPathFactoryBeanWithPrototypeResult() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONTEXT); assertNull(xbf.getType("tb.spouse")); assertEquals(TestBean.class, xbf.getType("propertyPath3")); Object result1 = xbf.getBean("tb.spouse"); Object result2 = xbf.getBean("propertyPath3"); Object result3 = xbf.getBean("propertyPath3"); assertTrue(result1 instanceof TestBean); assertTrue(result2 instanceof TestBean); assertTrue(result3 instanceof TestBean); assertEquals(11, ((TestBean) result1).getAge()); assertEquals(11, ((TestBean) result2).getAge()); assertEquals(11, ((TestBean) result3).getAge()); assertTrue(result1 != result2); assertTrue(result1 != result3); assertTrue(result2 != result3); }
@Test public void testMultiplePatterns() throws Throwable { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(CONTEXT); // This is a CGLIB proxy, so we can proxy it to the target class TestBean advised = (TestBean) bf.getBean("settersAndAbsquatulateAdvised"); // Interceptor behind regexp advisor NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor"); assertEquals(0, nop.getCount()); int newAge = 12; // Not advised advised.exceptional(null); assertEquals(0, nop.getCount()); // This is proxied advised.absquatulate(); assertEquals(1, nop.getCount()); advised.setAge(newAge); assertEquals(newAge, advised.getAge()); // Only setter fired assertEquals(2, nop.getCount()); }
@Test public void testAutowireWithUnsatisfiedConstructorDependency() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "Rod")); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("rod", bd); assertEquals(1, lbf.getBeanDefinitionCount()); try { lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true); fail("Should have unsatisfied constructor dependency on SideEffectBean"); } catch (UnsatisfiedDependencyException ex) { // expected } }
@Test public void testDependenciesMaterializeThis() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEP_MATERIALIZE_CONTEXT); assertEquals(2, xbf.getBeansOfType(DummyBo.class, true, false).size()); assertEquals(3, xbf.getBeansOfType(DummyBo.class, true, true).size()); assertEquals(3, xbf.getBeansOfType(DummyBo.class, true, false).size()); assertEquals(3, xbf.getBeansOfType(DummyBo.class).size()); assertEquals(2, xbf.getBeansOfType(DummyBoImpl.class, true, true).size()); assertEquals(1, xbf.getBeansOfType(DummyBoImpl.class, false, true).size()); assertEquals(2, xbf.getBeansOfType(DummyBoImpl.class).size()); DummyBoImpl bos = (DummyBoImpl) xbf.getBean("boSingleton"); DummyBoImpl bop = (DummyBoImpl) xbf.getBean("boPrototype"); assertNotSame(bos, bop); assertTrue(bos.dao == bop.dao); }
public static void main(String[] args)throws Exception { // �������·���µ�beans.xml�ļ�������Spring���� // ApplicationContext ctx = new // ClassPathXmlApplicationContext("beans.xml"); // Person p = (Person)ctx.getBean("chinese"); // ���������·���µ�beans.xml�ļ�����Resource���� Resource isr = new ClassPathResource("beans.xml"); // ����Ĭ�ϵ�BeanFactory���� DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // ��Ĭ�ϵ�BeanFactory��������isr��Ӧ��XML�����ļ� new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(isr); // ��ȡ�����е�Bean������ BeanPostProcessor bp = (BeanPostProcessor)beanFactory.getBean("bp"); // ע��Bean������ beanFactory.addBeanPostProcessor(bp); Person p = (Person)beanFactory.getBean("chinese"); p.useAxe(); }
@Test public void testCustomAnnotationOptionalFieldResourceInjection() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setAutowiredAnnotationType(MyAutowired.class); bpp.setRequiredParameterName("optional"); bpp.setRequiredParameterValue(false); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("customBean", new RootBeanDefinition( CustomAnnotationOptionalFieldResourceInjectionBean.class)); TestBean tb = new TestBean(); bf.registerSingleton("testBean", tb); CustomAnnotationOptionalFieldResourceInjectionBean bean = (CustomAnnotationOptionalFieldResourceInjectionBean) bf.getBean("customBean"); assertSame(tb, bean.getTestBean3()); assertNull(bean.getTestBean()); assertNull(bean.getTestBean2()); bf.destroySingletons(); }
@Test public void testGetBeanNamesForTypeBeforeFactoryBeanCreation() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); lbf.registerBeanDefinition("factoryBean", new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class)); assertFalse(lbf.containsSingleton("factoryBean")); String[] beanNames = lbf.getBeanNamesForType(Runnable.class, false, false); assertEquals(1, beanNames.length); assertEquals("&factoryBean", beanNames[0]); beanNames = lbf.getBeanNamesForType(Callable.class, false, false); assertEquals(1, beanNames.length); assertEquals("&factoryBean", beanNames[0]); beanNames = lbf.getBeanNamesForType(RepositoryFactoryInformation.class, false, false); assertEquals(1, beanNames.length); assertEquals("&factoryBean", beanNames[0]); beanNames = lbf.getBeanNamesForType(FactoryBean.class, false, false); assertEquals(1, beanNames.length); assertEquals("&factoryBean", beanNames[0]); }
@Test public void testLazyInitialization() { KnowsIfInstantiated.clearInstantiationRecord(); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Properties p = new Properties(); p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName()); p.setProperty("x1.(lazy-init)", "true"); assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); lbf.preInstantiateSingletons(); assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated()); lbf.getBean("x1"); assertTrue("singleton was instantiated", KnowsIfInstantiated.wasInstantiated()); }
@Test public void testGetBeanByTypeInstanceFiltersOutNonAutowireCandidates() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd1 = createConstructorDependencyBeanDefinition(99); RootBeanDefinition bd2 = createConstructorDependencyBeanDefinition(43); RootBeanDefinition na1 = createConstructorDependencyBeanDefinition(21); na1.setAutowireCandidate(false); lbf.registerBeanDefinition("bd1", bd1); lbf.registerBeanDefinition("na1", na1); ConstructorDependency actual = lbf.getBean(ConstructorDependency.class, 42); // na1 was filtered assertThat(actual.beanName, equalTo("bd1")); lbf.registerBeanDefinition("bd2", bd2); try { lbf.getBean(TestBean.class, 67); fail("Should have thrown NoSuchBeanDefinitionException"); } catch (NoSuchBeanDefinitionException ex) { // expected } }
@Test public void testWildcardCanBeUsedInNotificationListenersMap() throws Exception { String beanName = "charlesDexterWard"; BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition(beanName, testBean.getBeanDefinition()); factory.preInstantiateSingletons(); Object testBeanInstance = factory.getBean(beanName); MBeanExporter exporter = new MBeanExporter(); exporter.setServer(getServer()); Map<String, Object> beansToExport = new HashMap<String, Object>(); beansToExport.put("test:what=ever", testBeanInstance); exporter.setBeans(beansToExport); exporter.setBeanFactory(factory); StubNotificationListener listener = new StubNotificationListener(); exporter.setNotificationListenerMappings(Collections.singletonMap("*", listener)); start(exporter); }
@Test public void viaBeanRegistration() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("componentScanAnnotatedConfig", genericBeanDefinition(ComponentScanAnnotatedConfig.class).getBeanDefinition()); bf.registerBeanDefinition("configurationClassPostProcessor", genericBeanDefinition(ConfigurationClassPostProcessor.class).getBeanDefinition()); GenericApplicationContext ctx = new GenericApplicationContext(bf); ctx.refresh(); ctx.getBean(ComponentScanAnnotatedConfig.class); ctx.getBean(TestBean.class); assertThat("config class bean not found", ctx.containsBeanDefinition("componentScanAnnotatedConfig"), is(true)); assertThat("@ComponentScan annotated @Configuration class registered " + "as bean definition did not trigger component scanning as expected", ctx.containsBean("fooServiceImpl"), is(true)); }
@Test public void testObjectFactoryQualifierInjection() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierInjectionBean.class)); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean")); bf.registerBeanDefinition("testBean", bd); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean"); assertSame(bf.getBean("testBean"), bean.getTestBean()); bf.destroySingletons(); }
@Test public void testObjectFactoryWithBeanField() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryFieldInjectionBean.class)); bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); bf.setSerializationId("test"); ObjectFactoryFieldInjectionBean bean = (ObjectFactoryFieldInjectionBean) bf.getBean("annotatedBean"); assertSame(bf.getBean("testBean"), bean.getTestBean()); bean = (ObjectFactoryFieldInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean); assertSame(bf.getBean("testBean"), bean.getTestBean()); bf.destroySingletons(); }
@Test public void testFactoryBeanDidNotCreatePrototype() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); Properties p = new Properties(); p.setProperty("x1.(class)", DummyFactory.class.getName()); // Reset static state DummyFactory.reset(); p.setProperty("x1.singleton", "false"); assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); (new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p); assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); assertEquals(TestBean.class, lbf.getType("x1")); lbf.preInstantiateSingletons(); assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated()); lbf.getBean("x1"); assertEquals(TestBean.class, lbf.getType("x1")); assertTrue(lbf.containsBean("x1")); assertTrue(lbf.containsBean("&x1")); assertTrue("prototype was instantiated", DummyFactory.wasPrototypeCreated()); }