private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition) { if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { if ("property".equals(node.getNodeName()) || "property".equals(node.getLocalName())) { String name = ((Element) node).getAttribute("name"); if (name != null && name.length() > 0) { String value = ((Element) node).getAttribute("value"); String ref = ((Element) node).getAttribute("ref"); if (value != null && value.length() > 0) { beanDefinition.getPropertyValues().addPropertyValue(name, value); } else if (ref != null && ref.length() > 0) { beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref)); } else { throw new UnsupportedOperationException("Unsupported <property name=\"" + name + "\"> sub tag, Only supported <property name=\"" + name + "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />"); } } } } } } }
@Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { Class<?> testClass = mergedConfig.getTestClass(); FlywayTest flywayAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, FlywayTest.class); BeanDefinitionRegistry registry = getBeanDefinitionRegistry(context); RootBeanDefinition registrarDefinition = new RootBeanDefinition(); registrarDefinition.setBeanClass(PreloadableEmbeddedPostgresRegistrar.class); registrarDefinition.getConstructorArgumentValues() .addIndexedArgumentValue(0, databaseAnnotation); registrarDefinition.getConstructorArgumentValues() .addIndexedArgumentValue(1, flywayAnnotation); registry.registerBeanDefinition("preloadableEmbeddedPostgresRegistrar", registrarDefinition); }
@Override protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition( RepositoryConfigurationSource configurationSource) { RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition(TarantoolKeyValueTemplate.class); ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues(); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(0, new RuntimeBeanReference(TARANTOOL_OPS_IMPL_BEAN_NAME)); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(1, new RuntimeBeanReference(MAPPING_CONTEXT_BEAN_NAME)); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(2, new RuntimeBeanReference(TARANTOOL_CONVERTER_BEAN_NAME)); keyValueTemplateDefinition.setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate); return keyValueTemplateDefinition; }
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { builder.addPropertyReference("transactionManager", TxNamespaceHandler.getTransactionManagerName(element)); List<Element> txAttributes = DomUtils.getChildElementsByTagName(element, ATTRIBUTES_ELEMENT); if (txAttributes.size() > 1) { parserContext.getReaderContext().error( "Element <attributes> is allowed at most once inside element <advice>", element); } else if (txAttributes.size() == 1) { // Using attributes source. Element attributeSourceElement = txAttributes.get(0); RootBeanDefinition attributeSourceDefinition = parseAttributeSource(attributeSourceElement, parserContext); builder.addPropertyValue("transactionAttributeSource", attributeSourceDefinition); } else { // Assume annotations source. builder.addPropertyValue("transactionAttributeSource", new RootBeanDefinition("org.springframework.transaction.annotation.AnnotationTransactionAttributeSource")); } }
/** * Derive further bean definitions from the configuration classes in the registry. */ @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { RootBeanDefinition iabpp = new RootBeanDefinition(ImportAwareBeanPostProcessor.class); iabpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(IMPORT_AWARE_PROCESSOR_BEAN_NAME, iabpp); RootBeanDefinition ecbpp = new RootBeanDefinition(EnhancedConfigurationBeanPostProcessor.class); ecbpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(ENHANCED_CONFIGURATION_PROCESSOR_BEAN_NAME, ecbpp); int registryId = System.identityHashCode(registry); if (this.registriesPostProcessed.contains(registryId)) { throw new IllegalStateException( "postProcessBeanDefinitionRegistry already called for this post-processor against " + registry); } if (this.factoriesPostProcessed.contains(registryId)) { throw new IllegalStateException( "postProcessBeanFactory already called for this post-processor against " + registry); } this.registriesPostProcessed.add(registryId); processConfigBeanDefinitions(registry); }
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { builder.addPropertyReference("cacheManager", CacheNamespaceHandler.extractCacheManager(element)); CacheNamespaceHandler.parseKeyGenerator(element, builder.getBeanDefinition()); List<Element> cacheDefs = DomUtils.getChildElementsByTagName(element, DEFS_ELEMENT); if (cacheDefs.size() >= 1) { // Using attributes source. List<RootBeanDefinition> attributeSourceDefinitions = parseDefinitionsSources(cacheDefs, parserContext); builder.addPropertyValue("cacheOperationSources", attributeSourceDefinitions); } else { // Assume annotations source. builder.addPropertyValue("cacheOperationSources", new RootBeanDefinition( AnnotationCacheOperationSource.class)); } }
/** * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong> * parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes. */ private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) { RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class); advisorDefinition.setSource(parserContext.extractSource(advisorElement)); String adviceRef = advisorElement.getAttribute(ADVICE_REF); if (!StringUtils.hasText(adviceRef)) { parserContext.getReaderContext().error( "'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot()); } else { advisorDefinition.getPropertyValues().add( ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef)); } if (advisorElement.hasAttribute(ORDER_PROPERTY)) { advisorDefinition.getPropertyValues().add( ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY)); } return advisorDefinition; }
private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, Object source) { Assert.notNull(registry, "BeanDefinitionRegistry must not be null"); if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) { BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME); if (!cls.getName().equals(apcDefinition.getBeanClassName())) { int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName()); int requiredPriority = findPriorityForClass(cls); if (currentPriority < requiredPriority) { apcDefinition.setBeanClassName(cls.getName()); } } return null; } RootBeanDefinition beanDefinition = new RootBeanDefinition(cls); beanDefinition.setSource(source); beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition); return beanDefinition; }
@Override public BeanDefinition parse(Element element, ParserContext parserContext) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); String key = element.getAttribute("key"); String value = element.getAttribute("value"); String hide = element.getAttribute("hide"); if(CommonUtils.isTrue(hide)){ JSFContext.putGlobalVal(Constants.HIDE_KEY_PREFIX + key, value); } else { JSFContext.putGlobalVal(key, value); } beanDefinition.getPropertyValues().addPropertyValue("key", key); beanDefinition.getPropertyValues().addPropertyValue("value", value); beanDefinition.getPropertyValues().addPropertyValue("hide", Boolean.valueOf(hide)); return beanDefinition; }
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; }
@Test public void typeNestedSetBinding() throws Exception { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext context) { RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); csDef.getPropertyValues().add("converters", new TestBeanConverter()); RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); wbiDef.getPropertyValues().add("conversionService", csDef); RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); context.registerBeanDefinition("handlerAdapter", adapterDef); } }, NestedSetController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); request.addParameter("testBeanSet", new String[] {"1", "2"}); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); }
@Override protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition( RepositoryConfigurationSource configurationSource) { RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition( VaultKeyValueTemplate.class); ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues(); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(0, new RuntimeBeanReference(VAULT_ADAPTER_BEAN_NAME)); constructorArgumentValuesForKeyValueTemplate.addIndexedArgumentValue(1, new RuntimeBeanReference(VAULT_MAPPING_CONTEXT_BEAN_NAME)); keyValueTemplateDefinition .setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate); return keyValueTemplateDefinition; }
@Test public void testMethodInjectionWithMapAndMultipleMatches() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class)); bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class)); bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class)); try { bf.getBean("annotatedBean"); fail("should have failed, more than one bean of type"); } catch (BeanCreationException e) { // expected } bf.destroySingletons(); }
@Test public void testGenericsBasedFactoryBeanInjectionWithBeanDefinition() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); RootBeanDefinition bd = new RootBeanDefinition(RepositoryFactoryBeanInjectionBean.class); bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); bf.registerBeanDefinition("annotatedBean", bd); bf.registerBeanDefinition("repoFactoryBean", new RootBeanDefinition(RepositoryFactoryBean.class)); RepositoryFactoryBeanInjectionBean bean = (RepositoryFactoryBeanInjectionBean) bf.getBean("annotatedBean"); RepositoryFactoryBean repoFactoryBean = bf.getBean("&repoFactoryBean", RepositoryFactoryBean.class); assertSame(repoFactoryBean, bean.repositoryFactoryBean); }
@Test public void testCustomTypeConverterWithBeanReference() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); lbf.setTypeConverter(new CustomTypeConverter(nf)); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("myFloat", new RuntimeBeanReference("myFloat")); ConstructorArgumentValues cav = new ConstructorArgumentValues(); cav.addIndexedArgumentValue(0, "myName"); cav.addIndexedArgumentValue(1, "myAge"); lbf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class, cav, pvs)); lbf.registerSingleton("myFloat", "1,1"); TestBean testBean = (TestBean) lbf.getBean("testBean"); assertEquals("myName", testBean.getName()); assertEquals(5, testBean.getAge()); assertTrue(testBean.getMyFloat().floatValue() == 1.1f); }
protected void processSubstitutions(ConfigurableListableBeanFactory beanFactory) { if (substitutions != null) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; for (Map.Entry<String, String> entry : substitutions.entrySet()) { // replace bean with substitution bean if (beanFactory.containsBean(entry.getKey())) { String beanName = entry.getKey(); String beanClass = entry.getValue(); BeanDefinition definition = new RootBeanDefinition(beanClass); MutablePropertyValues propertyValues = definition.getPropertyValues(); propertyValues.add("substitutedBean", beanFactory.getBean(beanName)); registry.registerBeanDefinition(beanName, definition); } } } }
@Test public void standardHandleMethod() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class)); wac.refresh(); return wac; } }; portlet.init(new MockPortletConfig()); MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); MockRenderResponse response = new MockRenderResponse(); portlet.render(request, response); assertEquals("test", response.getContentAsString()); }
@Test public void testCustomAnnotationRequiredMethodResourceInjectionFailsWhenNoDependencyFound() { 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( CustomAnnotationRequiredMethodResourceInjectionBean.class)); try { bf.getBean("customBean"); fail("expected BeanCreationException; no dependency available for required method"); } catch (BeanCreationException e) { // expected } bf.destroySingletons(); }
@Test public void testResourceInjectionFromJndi() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor(); SimpleJndiBeanFactory resourceFactory = new SimpleJndiBeanFactory(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(); TestBean tb = new TestBean(); jndiTemplate.addObject("java:comp/env/testBean", tb); TestBean tb2 = new TestBean(); jndiTemplate.addObject("java:comp/env/testBean2", tb2); resourceFactory.setJndiTemplate(jndiTemplate); bpp.setResourceFactory(resourceFactory); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ResourceInjectionBean.class)); ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean"); assertTrue(bean.initCalled); assertTrue(bean.init2Called); assertSame(tb, bean.getTestBean()); assertSame(tb2, bean.getTestBean2()); bf.destroySingletons(); assertTrue(bean.destroyCalled); assertTrue(bean.destroy2Called); }
@Test public void whenCacheManagerBeanAlreadyInContextThenMemcachedWithNonCustomConfigurationLoaded() { // add cache manager to the context before triggering auto-configuration on context load ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(mock(MemcachedClient.class)); RootBeanDefinition cacheManagerBeanDefinition = new RootBeanDefinition( MemcachedCacheManager.class, constructorArgumentValues, null); applicationContext.registerBeanDefinition("cacheManager", cacheManagerBeanDefinition); loadContext(CacheConfiguration.class, "memcached.cache.expiration=3600", "memcached.cache.prefix=custom:prefix", "memcached.cache.namespace=custom_namespace"); MemcachedCacheManager memcachedCacheManager = this.applicationContext.getBean(MemcachedCacheManager.class); assertThat(memcachedCacheManager) .as("Auto-configured disposable instance should not be loaded in context") .isNotInstanceOf(MemcachedCacheAutoConfiguration.DisposableMemcachedCacheManager.class); assertMemcachedCacheManager(memcachedCacheManager, Default.EXPIRATION, Default.PREFIX, Default.NAMESPACE); }
@Test @SuppressWarnings("serial") public void emptyRequestMapping() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerWithEmptyMapping.class)); RootBeanDefinition mbd = new RootBeanDefinition(ControllerClassNameHandlerMapping.class); mbd.getPropertyValues().add("excludedPackages", null); mbd.getPropertyValues().add("order", 0); wac.registerBeanDefinition("mapping", mbd); wac.registerBeanDefinition("mapping2", new RootBeanDefinition(DefaultAnnotationHandlerMapping.class)); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/servletannotationcontrollertests.controllerwithemptymapping"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("test", response.getContentAsString()); }
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String useLocal = AppContext.getProperty("cuba.useLocalServiceInvocation"); if (Boolean.valueOf(useLocal)) { log.info("Configuring proxy beans for local service invocations: " + services.keySet()); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; for (Map.Entry<String, String> entry : services.entrySet()) { String name = entry.getKey(); String serviceInterface = entry.getValue(); BeanDefinition definition = new RootBeanDefinition(LocalServiceProxy.class); MutablePropertyValues propertyValues = definition.getPropertyValues(); propertyValues.add("serviceName", name); propertyValues.add("serviceInterface", serviceInterface); registry.registerBeanDefinition(name, definition); log.debug("Configured proxy bean " + name + " of type " + serviceInterface); } processSubstitutions(beanFactory); } else { super.postProcessBeanFactory(beanFactory); } }
@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 testPublicSpecificExtendedPersistenceContextSetter() throws Exception { EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class); EntityManager mockEm2 = mock(EntityManager.class); given(mockEmf2.createEntityManager()).willReturn(mockEm2); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); gac.getDefaultListableBeanFactory().registerSingleton("unit2", mockEmf2); gac.registerBeanDefinition("annotationProcessor", new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class)); gac.registerBeanDefinition(SpecificPublicPersistenceContextSetter.class.getName(), new RootBeanDefinition(SpecificPublicPersistenceContextSetter.class)); gac.refresh(); SpecificPublicPersistenceContextSetter bean = (SpecificPublicPersistenceContextSetter) gac.getBean( SpecificPublicPersistenceContextSetter.class.getName()); assertNotNull(bean.getEntityManager()); bean.getEntityManager().flush(); verify(mockEm2).getTransaction(); verify(mockEm2).flush(); }
@Test public void testCustomAnnotationRequiredMethodResourceInjection() { 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( CustomAnnotationRequiredMethodResourceInjectionBean.class)); TestBean tb = new TestBean(); bf.registerSingleton("testBean", tb); CustomAnnotationRequiredMethodResourceInjectionBean bean = (CustomAnnotationRequiredMethodResourceInjectionBean) bf.getBean("customBean"); assertSame(tb, bean.getTestBean()); bf.destroySingletons(); }
@Test public void testConstructorResourceInjectionWithMultipleCandidatesAsCollection() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); bpp.setBeanFactory(bf); bf.addBeanPostProcessor(bpp); bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition( ConstructorsCollectionResourceInjectionBean.class)); TestBean tb = new TestBean(); bf.registerSingleton("testBean", tb); NestedTestBean ntb1 = new NestedTestBean(); bf.registerSingleton("nestedTestBean1", ntb1); NestedTestBean ntb2 = new NestedTestBean(); bf.registerSingleton("nestedTestBean2", ntb2); ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean"); assertNull(bean.getTestBean3()); assertSame(tb, bean.getTestBean4()); assertEquals(2, bean.getNestedTestBeans().size()); assertSame(ntb1, bean.getNestedTestBeans().get(0)); assertSame(ntb2, bean.getNestedTestBeans().get(1)); bf.destroySingletons(); }
@Test public void testPrototypeCreationWithResolvedPropertiesIsFastEnough() { Assume.group(TestGroup.PERFORMANCE); Assume.notLogging(factoryLog); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class); rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); rbd.getPropertyValues().add("spouse", new RuntimeBeanReference("spouse")); lbf.registerBeanDefinition("test", rbd); lbf.registerBeanDefinition("spouse", new RootBeanDefinition(TestBean.class)); TestBean spouse = (TestBean) lbf.getBean("spouse"); StopWatch sw = new StopWatch(); sw.start("prototype"); for (int i = 0; i < 100000; i++) { TestBean tb = (TestBean) lbf.getBean("test"); assertSame(spouse, tb.getSpouse()); } sw.stop(); // System.out.println(sw.getTotalTimeMillis()); assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000); }
@Test public void testCustomAnnotationRequiredMethodResourceInjectionFailsWhenMultipleDependenciesFound() { 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( CustomAnnotationRequiredMethodResourceInjectionBean.class)); TestBean tb1 = new TestBean(); bf.registerSingleton("testBean1", tb1); TestBean tb2 = new TestBean(); bf.registerSingleton("testBean2", tb2); try { bf.getBean("customBean"); fail("expected BeanCreationException; multiple beans of dependency type available"); } catch (BeanCreationException e) { // expected } bf.destroySingletons(); }
private void registerWebSocketMessageBrokerStats(RootBeanDefinition broker, RuntimeBeanReference inChannel, RuntimeBeanReference outChannel, ParserContext context, Object source) { RootBeanDefinition beanDef = new RootBeanDefinition(WebSocketMessageBrokerStats.class); RuntimeBeanReference webSocketHandler = new RuntimeBeanReference(WEB_SOCKET_HANDLER_BEAN_NAME); beanDef.getPropertyValues().add("subProtocolWebSocketHandler", webSocketHandler); if (StompBrokerRelayMessageHandler.class == broker.getBeanClass()) { beanDef.getPropertyValues().add("stompBrokerRelay", broker); } String name = inChannel.getBeanName() + "Executor"; if (context.getRegistry().containsBeanDefinition(name)) { beanDef.getPropertyValues().add("inboundChannelExecutor", context.getRegistry().getBeanDefinition(name)); } name = outChannel.getBeanName() + "Executor"; if (context.getRegistry().containsBeanDefinition(name)) { beanDef.getPropertyValues().add("outboundChannelExecutor", context.getRegistry().getBeanDefinition(name)); } name = SCHEDULER_BEAN_NAME; if (context.getRegistry().containsBeanDefinition(name)) { beanDef.getPropertyValues().add("sockJsTaskScheduler", context.getRegistry().getBeanDefinition(name)); } registerBeanDefByName("webSocketMessageBrokerStats", beanDef, context, source); }
@Test public void repro() { AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext(); bf.registerBeanDefinition("fooConfig", new RootBeanDefinition(FooConfig.class)); bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); bf.refresh(); assertThat(bf.getBean("foo"), instanceOf(Foo.class)); assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); @SuppressWarnings("rawtypes") Map<String, FactoryBean> fbBeans = bf.getBeansOfType(FactoryBean.class); assertThat(1, equalTo(fbBeans.size())); assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); Map<String, AnInterface> aiBeans = bf.getBeansOfType(AnInterface.class); assertThat(1, equalTo(aiBeans.size())); assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); }
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) { ManagedList<Object> result = new ManagedList<Object>(); for (Object object : list) { if (object instanceof BeanDefinitionHolder) { BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object; String className = beanDef.getBeanDefinition().getBeanClassName(); Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader()); if (WebArgumentResolver.class.isAssignableFrom(clazz)) { RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class); adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef); result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter")); continue; } } result.add(object); } return result; }
@Test public void testAutowireBeanByTypeWithTwoPrimaryCandidates() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPrimary(true); RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); bd2.setPrimary(true); lbf.registerBeanDefinition("test", bd); lbf.registerBeanDefinition("spouse", bd2); try { lbf.autowire(DependenciesBean.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); fail("Should have thrown UnsatisfiedDependencyException"); } catch (UnsatisfiedDependencyException ex) { // expected assertNotNull("Exception should have cause", ex.getCause()); assertEquals("Wrong cause type", NoUniqueBeanDefinitionException.class, ex.getCause().getClass()); } }
@Test @SuppressWarnings("resource") public void testFormatFieldForValueInjectionUsingMetaAnnotations() { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); RootBeanDefinition bd = new RootBeanDefinition(MetaValueBean.class); bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); ac.registerBeanDefinition("valueBean", bd); ac.registerBeanDefinition("conversionService", new RootBeanDefinition(FormattingConversionServiceFactoryBean.class)); ac.registerBeanDefinition("ppc", new RootBeanDefinition(PropertyPlaceholderConfigurer.class)); ac.refresh(); System.setProperty("myDate", "10-31-09"); System.setProperty("myNumber", "99.99%"); try { MetaValueBean valueBean = ac.getBean(MetaValueBean.class); assertEquals(new LocalDate(2009, 10, 31), new LocalDate(valueBean.date)); assertEquals(Double.valueOf(0.9999), valueBean.number); } finally { System.clearProperty("myDate"); System.clearProperty("myNumber"); } }
@Test public void jsonMapConversionWithCustomObjectMapper() throws Exception { this.context = new GenericApplicationContext(); ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); constructorArgs.addIndexedArgumentValue(0, objectMapper); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class, constructorArgs, null)); this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(JsonMapConversionEndpoint.class)); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); Object response = mbeanExporter.getServer().invoke( getObjectName("endpoint1", this.context), "getData", new Object[0], new String[0]); assertThat(response).isInstanceOf(Map.class); assertThat(((Map<?, ?>) response).get("date")).isInstanceOf(String.class); }
@Test public void testRegistrationWithParentContext() throws Exception { this.context = new GenericApplicationContext(); this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class)); this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(TestEndpoint.class)); GenericApplicationContext parent = new GenericApplicationContext(); this.context.setParent(parent); parent.refresh(); this.context.refresh(); MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class); assertThat(mbeanExporter.getServer() .getMBeanInfo(getObjectName("endpoint1", this.context))).isNotNull(); parent.close(); }