Java Code Examples for org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition()

The following examples show how to use org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testDoubleArrayConstructorWithAutowiring() throws MalformedURLException {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerSingleton("integer1", new Integer(4));
	bf.registerSingleton("integer2", new Integer(5));
	bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
	bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));

	RootBeanDefinition rbd = new RootBeanDefinition(ArrayBean.class);
	rbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	bf.registerBeanDefinition("arrayBean", rbd);
	ArrayBean ab = (ArrayBean) bf.getBean("arrayBean");

	assertEquals(new Integer(4), ab.getIntegerArray()[0]);
	assertEquals(new Integer(5), ab.getIntegerArray()[1]);
	assertEquals(new UrlResource("http://localhost:8080"), ab.getResourceArray()[0]);
	assertEquals(new UrlResource("http://localhost:9090"), ab.getResourceArray()[1]);
}
 
Example 2
Source File: GlobalBeanDefinitionUtilsTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void retrieveResourceIdResolverBeanName_resourceIdResolverBeanAlreadyRegistered_returnsInternalBeanName() {
	// Arrange
	BeanDefinition resourceIdResolverBeanDefinition = new GenericBeanDefinition();

	DefaultListableBeanFactory registry = new DefaultListableBeanFactory();
	registry.registerBeanDefinition(
			GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME,
			resourceIdResolverBeanDefinition);

	// Act
	String resourceIdResolverBeanName = GlobalBeanDefinitionUtils
			.retrieveResourceIdResolverBeanName(registry);

	// Assert
	assertThat(resourceIdResolverBeanName)
			.isEqualTo(GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME);
}
 
Example 3
Source File: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void ignoredNestedUnresolvablePlaceholder() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
					.addPropertyValue("name", "${my.name}")
					.getBeanDefinition());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setProperties(new Properties() {{
		put("my.name", "${bogus}");
	}});
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${bogus}"));
}
 
Example 4
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSingletonLookupByTypeIsFastEnough() {
	Assume.group(TestGroup.PERFORMANCE);
	Assume.notLogging(factoryLog);
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class));
	lbf.freezeConfiguration();
	StopWatch sw = new StopWatch();
	sw.start("singleton");
	for (int i = 0; i < 1000000; i++) {
		lbf.getBean(TestBean.class);
	}
	sw.stop();
	// System.out.println(sw.getTotalTimeMillis());
	assertTrue("Singleton lookup took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 1000);
}
 
Example 6
Source File: RequiredAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testWithThreeRequiredPropertiesOmitted() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.addPropertyValue("name", "Rob Harrop")
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Properties"));
		assertTrue(message.contains("age"));
		assertTrue(message.contains("favouriteColour"));
		assertTrue(message.contains("jobTitle"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example 7
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplicitDependsOnCycle() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
	bd1.setDependsOn("tb2");
	lbf.registerBeanDefinition("tb1", bd1);
	RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
	bd2.setDependsOn("tb3");
	lbf.registerBeanDefinition("tb2", bd2);
	RootBeanDefinition bd3 = new RootBeanDefinition(TestBean.class);
	bd3.setDependsOn("tb1");
	lbf.registerBeanDefinition("tb3", bd3);
	try {
		lbf.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		assertTrue(ex.getMessage().contains("Circular"));
		assertTrue(ex.getMessage().contains("'tb3'"));
		assertTrue(ex.getMessage().contains("'tb1'"));
	}
}
 
Example 8
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceInjection() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition bd = new RootBeanDefinition(ResourceInjectionBean.class);
	bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", bd);
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);

	ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());

	bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb, bean.getTestBean());
	assertSame(tb, bean.getTestBean2());
}
 
Example 9
Source File: MBeanExporterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testOnlyBonaFideMBeanIsExportedWhenAutodetectIsMBeanOnly() throws Exception {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(OBJECT_NAME, builder.getBeanDefinition());
	String exportedBeanName = "spring:type=TestBean";
	factory.registerSingleton(exportedBeanName, new TestBean());

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	exporter.setAssembler(new NamedBeanAutodetectCapableMBeanInfoAssemblerStub(exportedBeanName));
	exporter.setBeanFactory(factory);
	exporter.setAutodetectMode(MBeanExporter.AUTODETECT_MBEAN);
	start(exporter);

	assertIsRegistered("Bona fide MBean not autodetected in AUTODETECT_MBEAN mode",
			ObjectNameManager.getInstance(OBJECT_NAME));
	assertIsNotRegistered("Bean autodetected and (only) AUTODETECT_MBEAN mode is on",
			ObjectNameManager.getInstance(exportedBeanName));
}
 
Example 10
Source File: AutowireWithExclusionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryInParentAndChild() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	parent.getBeanDefinition("props1").setPrimary(true);
	parent.preInstantiateSingletons();
	DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
	RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class);
	robDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally"));
	child.registerBeanDefinition("rob2", robDef);
	RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class);
	propsDef.getPropertyValues().add("properties", "name=props3");
	propsDef.setPrimary(true);
	child.registerBeanDefinition("props3", propsDef);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props3", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example 11
Source File: CommonAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceInjection() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
	bpp.setResourceFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ResourceInjectionBean.class));
	TestBean tb = new TestBean();
	bf.registerSingleton("testBean", tb);
	TestBean tb2 = new TestBean();
	bf.registerSingleton("testBean2", tb2);

	ResourceInjectionBean bean = (ResourceInjectionBean) bf.getBean("annotatedBean");
	assertTrue(bean.initCalled);
	assertTrue(bean.init2Called);
	assertTrue(bean.init3Called);
	assertSame(tb, bean.getTestBean());
	assertSame(tb2, bean.getTestBean2());
	bf.destroySingletons();
	assertTrue(bean.destroyCalled);
	assertTrue(bean.destroy2Called);
	assertTrue(bean.destroy3Called);
}
 
Example 12
Source File: BeanConfigurerSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void configureBeanReallyDoesDefaultToUsingTheFullyQualifiedClassNameOfTheSuppliedBeanInstance() throws Exception {
	TestBean beanInstance = new TestBean();
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
	builder.addPropertyValue("name", "Harriet Wheeler");

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(beanInstance.getClass().getName(), builder.getBeanDefinition());

	BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
	configurer.setBeanFactory(factory);
	configurer.afterPropertiesSet();
	configurer.configureBean(beanInstance);
	assertEquals("Bean is evidently not being configured (for some reason)", "Harriet Wheeler", beanInstance.getName());
}
 
Example 13
Source File: PropertySourcesPlaceholderConfigurerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void trimValuesIsOffByDefault() {
	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean", rootBeanDefinition(TestBean.class)
			.addPropertyValue("name", "${my.name}")
			.getBeanDefinition());
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", " myValue  "));
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo(" myValue  "));
}
 
Example 14
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testGetBeanByTypeWithMultiplePrimary() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
	bd1.setPrimary(true);
	RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
	bd2.setPrimary(true);
	lbf.registerBeanDefinition("bd1", bd1);
	lbf.registerBeanDefinition("bd2", bd2);
	assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() ->
			lbf.getBean(TestBean.class))
		.withMessageContaining("more than one 'primary'");
}
 
Example 15
Source File: AutoConfiguration.java    From krpc with Apache License 2.0 5 votes vote down vote up
void registerAsyncReferer(String beanName, String interfaceName, DefaultListableBeanFactory beanFactory) {
    //log.info("register referer "+interfaceName+", beanName="+beanName);
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RefererFactory.class);
    beanDefinitionBuilder.addConstructorArgValue(beanName);
    beanDefinitionBuilder.addConstructorArgValue(interfaceName);
    beanDefinitionBuilder.addDependsOn("rpcApp");
    beanDefinitionBuilder.setLazyInit(true);
    beanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getRawBeanDefinition());
}
 
Example 16
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testSmartInitFactory() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.registerBeanDefinition("test", new RootBeanDefinition(EagerInitFactory.class));
	lbf.preInstantiateSingletons();
	EagerInitFactory factory = (EagerInitFactory) lbf.getBean("&test");
	assertTrue(factory.initialized);
}
 
Example 17
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testConstructorDependencyWithClassResolution() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyWithClassResolution.class);
	bd.getConstructorArgumentValues().addGenericArgumentValue("java.lang.String");
	lbf.registerBeanDefinition("test", bd);
	lbf.preInstantiateSingletons();
}
 
Example 18
Source File: MBeanExporterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception {
	BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.rootBeanDefinition(Person.class);
	BeanDefinitionBuilder builder2 = BeanDefinitionBuilder
			.rootBeanDefinition(RuntimeExceptionThrowingConstructorBean.class);

	String objectName1 = "spring:test=bean1";
	String objectName2 = "spring:test=bean2";

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(objectName1, builder1.getBeanDefinition());
	factory.registerBeanDefinition(objectName2, builder2.getBeanDefinition());

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	Map<String, Object> beansToExport = new HashMap<String, Object>();
	beansToExport.put(objectName1, objectName1);
	beansToExport.put(objectName2, objectName2);
	exporter.setBeans(beansToExport);
	exporter.setBeanFactory(factory);

	try {
		start(exporter);
		fail("Must have failed during creation of RuntimeExceptionThrowingConstructorBean");
	}
	catch (RuntimeException expected) {
	}

	assertIsNotRegistered("Must have unregistered all previously registered MBeans due to RuntimeException",
			ObjectNameManager.getInstance(objectName1));
	assertIsNotRegistered("Must have never registered this MBean due to RuntimeException",
			ObjectNameManager.getInstance(objectName2));
}
 
Example 19
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBeanByTypeWithMultiplePriority() throws Exception {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
	RootBeanDefinition bd1 = new RootBeanDefinition(HighPriorityTestBean.class);
	RootBeanDefinition bd2 = new RootBeanDefinition(HighPriorityTestBean.class);
	lbf.registerBeanDefinition("bd1", bd1);
	lbf.registerBeanDefinition("bd2", bd2);
	thrown.expect(NoUniqueBeanDefinitionException.class);
	thrown.expectMessage(containsString("Multiple beans found with the same priority"));
	thrown.expectMessage(containsString("5")); // conflicting priority
	lbf.getBean(TestBean.class);
}
 
Example 20
Source File: MutiRouteDataSource.java    From azeroth with Apache License 2.0 4 votes vote down vote up
/**
 * 功能说明:根据DataSource创建bean并注册到容器中
 * @param mapCustom
 * @param isLatestGroup
 */
private void registerDataSources(Map<String, DataSourceInfo> mapCustom) {

    DefaultListableBeanFactory acf = (DefaultListableBeanFactory) this.context.getAutowireCapableBeanFactory();
    Iterator<String> iter = mapCustom.keySet().iterator();

    Map<Object, DataSource> targetDataSources = new HashMap<>();

    while (iter.hasNext()) {
        String dsKey = iter.next();  //
        DataSourceInfo dataSourceInfo = mapCustom.get(dsKey);
        //如果当前库为最新一组数据库,注册beanName为master

        logger.info(">>>>>begin to initialize datasource:" + dsKey + "\n================\n" + dataSourceInfo.toString()
                + "\n==============");

        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(DruidDataSource.class);
        beanDefinitionBuilder.addPropertyValue("driverClassName", dataSourceInfo.driveClassName);
        beanDefinitionBuilder.addPropertyValue("url", dataSourceInfo.connUrl);
        beanDefinitionBuilder.addPropertyValue("username", dataSourceInfo.userName);
        beanDefinitionBuilder.addPropertyValue("password", dataSourceInfo.password);
        //
        beanDefinitionBuilder.addPropertyValue("testWhileIdle", true);
        beanDefinitionBuilder.addPropertyValue("validationQuery", "SELECT 'x'");

        if (dataSourceInfo.initialSize > 0) {
            beanDefinitionBuilder.addPropertyValue("initialSize", dataSourceInfo.initialSize);
        }
        if (dataSourceInfo.maxActive > 0) {
            beanDefinitionBuilder.addPropertyValue("maxActive", dataSourceInfo.maxActive);
        }
        if (dataSourceInfo.maxIdle > 0) {
            beanDefinitionBuilder.addPropertyValue("maxIdle", dataSourceInfo.maxIdle);
        }
        if (dataSourceInfo.minIdle > 0) {
            beanDefinitionBuilder.addPropertyValue("minIdle", dataSourceInfo.minIdle);
        }

        if (dataSourceInfo.maxWait > 0) {
            beanDefinitionBuilder.addPropertyValue("maxWait", dataSourceInfo.maxWait);
        }

        if (dataSourceInfo.minEvictableIdleTimeMillis > 0) {
            beanDefinitionBuilder.addPropertyValue("minEvictableIdleTimeMillis", dataSourceInfo.minEvictableIdleTimeMillis);
        }

        if (dataSourceInfo.timeBetweenEvictionRunsMillis > 0) {
            beanDefinitionBuilder.addPropertyValue("timeBetweenEvictionRunsMillis", dataSourceInfo.timeBetweenEvictionRunsMillis);
        }

        if (dataSourceInfo.maxWait > 0) {
            beanDefinitionBuilder.addPropertyValue("maxWait", dataSourceInfo.maxWait);
        }

        beanDefinitionBuilder.addPropertyValue("testOnBorrow", dataSourceInfo.testOnBorrow);
        beanDefinitionBuilder.addPropertyValue("testOnReturn", dataSourceInfo.testOnReturn);

        acf.registerBeanDefinition(dsKey, beanDefinitionBuilder.getRawBeanDefinition());

        DruidDataSource ds = (DruidDataSource) this.context.getBean(dsKey);

        targetDataSources.put(dsKey, ds);

        // 设置默认数据源
        if (dataSourceInfo.dbGroupIndex == dbGroupNums - 1) {
            defaultDataSource = ds;
        }
        logger.info("bean[" + dsKey + "] has initialized! lookupKey:" + dsKey);

        //
        DataSourceContextHolder.get().registerDataSourceKey(dsKey);
    }

    addTargetDataSources(targetDataSources);
}