org.springframework.beans.factory.support.DefaultListableBeanFactory Java Examples

The following examples show how to use org.springframework.beans.factory.support.DefaultListableBeanFactory. 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: ComponentScanAnnotationIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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));
}
 
Example #2
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 #3
Source File: PropertiesBeanDefinitionReaderDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 创建 IoC 底层容器
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    // 创建面向 Properties 资源的 BeanDefinitionReader 示例
    PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);
    // Properties 资源加载默认通过 ISO-8859-1,实际存储 UTF-8
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    // 通过指定的 ClassPath 获取 Resource 对象
    Resource resource = resourceLoader.getResource("classpath:/META-INF/user-bean-definitions.properties");
    // 转换成带有字符编码 EncodedResource 对象
    EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
    int beanDefinitionsCount = beanDefinitionReader.loadBeanDefinitions(encodedResource);
    System.out.println(String.format("已记载 %d 个 BeanDefinition\n", beanDefinitionsCount));
    // 通过依赖查找获取 User Bean
    User user = beanFactory.getBean("user", User.class);
    System.out.println(user);
}
 
Example #4
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testRegisterExistingSingletonWithAutowire() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "Tony");
	pvs.add("age", "48");
	RootBeanDefinition bd = new RootBeanDefinition(DependenciesBean.class);
	bd.setPropertyValues(pvs);
	bd.setDependencyCheck(RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
	bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	lbf.registerBeanDefinition("test", bd);
	Object singletonObject = new TestBean();
	lbf.registerSingleton("singletonObject", singletonObject);

	assertTrue(lbf.containsBean("singletonObject"));
	assertTrue(lbf.isSingleton("singletonObject"));
	assertEquals(TestBean.class, lbf.getType("singletonObject"));
	assertEquals(0, lbf.getAliases("singletonObject").length);
	DependenciesBean test = (DependenciesBean) lbf.getBean("test");
	assertEquals(singletonObject, lbf.getBean("singletonObject"));
	assertEquals(singletonObject, test.getSpouse());
}
 
Example #5
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testGetBeanByTypeFiltersOutNonAutowireCandidates() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
	RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class);
	RootBeanDefinition na1 = new RootBeanDefinition(TestBean.class);
	na1.setAutowireCandidate(false);

	lbf.registerBeanDefinition("bd1", bd1);
	lbf.registerBeanDefinition("na1", na1);
	TestBean actual = lbf.getBean(TestBean.class);  // na1 was filtered
	assertSame(lbf.getBean("bd1", TestBean.class), actual);

	lbf.registerBeanDefinition("bd2", bd2);
	try {
		lbf.getBean(TestBean.class);
		fail("Should have thrown NoSuchBeanDefinitionException");
	}
	catch (NoSuchBeanDefinitionException ex) {
		// expected
	}
}
 
Example #6
Source File: AutowiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectFactoryInjectionIntoPrototypeBean() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	RootBeanDefinition annotatedBeanDefinition = new RootBeanDefinition(ObjectFactoryInjectionBean.class);
	annotatedBeanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	bf.registerBeanDefinition("annotatedBean", annotatedBeanDefinition);
	bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));

	ObjectFactoryInjectionBean bean = (ObjectFactoryInjectionBean) bf.getBean("annotatedBean");
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	ObjectFactoryInjectionBean anotherBean = (ObjectFactoryInjectionBean) bf.getBean("annotatedBean");
	assertNotSame(anotherBean, bean);
	assertSame(bf.getBean("testBean"), anotherBean.getTestBean());
}
 
Example #7
Source File: PropertySourcesPlaceholderConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void explicitPropertySourcesExcludesEnvironment() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	bf.registerBeanDefinition("testBean",
			genericBeanDefinition(TestBean.class)
				.addPropertyValue("name", "${my.name}")
				.getBeanDefinition());

	MutablePropertySources propertySources = new MutablePropertySources();
	propertySources.addLast(new MockPropertySource());

	PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
	ppc.setPropertySources(propertySources);
	ppc.setEnvironment(new MockEnvironment().withProperty("my.name", "env"));
	ppc.setIgnoreUnresolvablePlaceholders(true);
	ppc.postProcessBeanFactory(bf);
	assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
	assertEquals(ppc.getAppliedPropertySources().iterator().next(), propertySources.iterator().next());
}
 
Example #8
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testConfigureBeanWithAutowiring() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	lbf.registerBeanDefinition("spouse", bd);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("age", "99");
	RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
	tbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_NAME);
	lbf.registerBeanDefinition("test", tbd);
	TestBean tb = new TestBean();
	lbf.configureBean(tb, "test");
	assertSame(lbf, tb.getBeanFactory());
	TestBean spouse = (TestBean) lbf.getBean("spouse");
	assertEquals(spouse, tb.getSpouse());
}
 
Example #9
Source File: ProxyFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testGetObjectTypeWithNoTargetOrTargetSource() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(TARGETSOURCE_CONTEXT, CLASS));

	ITestBean tb = (ITestBean) bf.getBean("noTarget");
	try {
		tb.getName();
		fail();
	}
	catch (UnsupportedOperationException ex) {
		assertEquals("getName", ex.getMessage());
	}
	FactoryBean<?> pfb = (ProxyFactoryBean) bf.getBean("&noTarget");
	assertTrue("Has correct object type", ITestBean.class.isAssignableFrom(pfb.getObjectType()));
}
 
Example #10
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterExistingSingletonWithAutowire() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "Tony");
	pvs.add("age", "48");
	RootBeanDefinition bd = new RootBeanDefinition(DependenciesBean.class);
	bd.setPropertyValues(pvs);
	bd.setDependencyCheck(RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
	bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_TYPE);
	lbf.registerBeanDefinition("test", bd);
	Object singletonObject = new TestBean();
	lbf.registerSingleton("singletonObject", singletonObject);

	assertTrue(lbf.containsBean("singletonObject"));
	assertTrue(lbf.isSingleton("singletonObject"));
	assertEquals(TestBean.class, lbf.getType("singletonObject"));
	assertEquals(0, lbf.getAliases("singletonObject").length);
	DependenciesBean test = (DependenciesBean) lbf.getBean("test");
	assertEquals(singletonObject, lbf.getBean("singletonObject"));
	assertEquals(singletonObject, test.getSpouse());
}
 
Example #11
Source File: BeanConfigurerSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void configureBeanPerformsAutowiringByNameIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception {
	TestBean beanInstance = new TestBean();
	// spouse for autowiring by name...
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class);
	builder.addConstructorArgValue("David Gavurin");

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition("spouse", builder.getBeanDefinition());

	BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class);
	given(resolver.resolveWiringInfo(beanInstance)).willReturn(new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, false));

	BeanConfigurerSupport configurer = new StubBeanConfigurerSupport();
	configurer.setBeanFactory(factory);
	configurer.setBeanWiringInfoResolver(resolver);
	configurer.configureBean(beanInstance);
	assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName());
}
 
Example #12
Source File: AutowireWithExclusionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryInParentFactory() 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");
	child.registerBeanDefinition("props3", propsDef);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props1", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example #13
Source File: FactoryMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testFactoryMethodsWithNullInstance() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

	assertEquals("null", xbf.getBean("null").toString());

	try {
		xbf.getBean("nullWithProperty");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
	}
}
 
Example #14
Source File: PropertyPathFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #15
Source File: CommonAnnotationBeanPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testResourceInjectionWithDefaultMethod() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(DefaultMethodResourceInjectionBean.class));
	TestBean tb2 = new TestBean();
	bf.registerSingleton("testBean2", tb2);
	NestedTestBean tb7 = new NestedTestBean();
	bf.registerSingleton("testBean7", tb7);

	DefaultMethodResourceInjectionBean bean = (DefaultMethodResourceInjectionBean) bf.getBean("annotatedBean");
	assertSame(tb2, bean.getTestBean2());
	assertSame(2, bean.counter);

	bf.destroySingletons();
	assertSame(3, bean.counter);
}
 
Example #16
Source File: XmlBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCircularReferencesWithWrappingAndRawInjectionAllowed() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	xbf.setAllowRawInjectionDespiteWrapping(true);
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
	reader.loadBeanDefinitions(REFTYPES_CONTEXT);
	xbf.addBeanPostProcessor(new WrappingPostProcessor());

	ITestBean jenny = (ITestBean) xbf.getBean("jenny");
	ITestBean david = (ITestBean) xbf.getBean("david");
	assertTrue(AopUtils.isAopProxy(jenny));
	assertTrue(AopUtils.isAopProxy(david));
	assertSame(david, jenny.getSpouse());
	assertNotSame(jenny, david.getSpouse());
	assertEquals("Jenny", david.getSpouse().getName());
	assertSame(david, david.getSpouse().getSpouse());
	assertTrue(AopUtils.isAopProxy(jenny.getSpouse()));
	assertTrue(!AopUtils.isAopProxy(david.getSpouse()));
}
 
Example #17
Source File: XmlBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * When using a BeanFactory. singletons are of course not pre-instantiated.
 * So rubbish class names in bean defs must now not be 'resolved' when the
 * bean def is being parsed, 'cos everything on a bean def is now lazy, but
 * must rather only be picked up when the bean is instantiated.
 */
@Test
public void testClassNotFoundWithDefaultBeanClassLoader() {
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(factory).loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT);
	// cool, no errors, so the rubbish class name in the bean def was not resolved
	try {
		// let's resolve the bean definition; must blow up
		factory.getBean("classNotFound");
		fail("Must have thrown a CannotLoadBeanClassException");
	}
	catch (CannotLoadBeanClassException ex) {
		assertTrue(ex.getResourceDescription().contains("classNotFound.xml"));
		assertTrue(ex.getCause() instanceof ClassNotFoundException);
	}
}
 
Example #18
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testStaticPrototypeFactoryMethodFoundByNonEagerTypeMatching() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition rbd = new RootBeanDefinition(TestBeanFactory.class);
	rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	rbd.setFactoryMethodName("createTestBean");
	lbf.registerBeanDefinition("x1", rbd);

	TestBeanFactory.initialized = false;
	String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
	assertEquals(1, beanNames.length);
	assertEquals("x1", beanNames[0]);
	assertFalse(lbf.containsSingleton("x1"));
	assertTrue(lbf.containsBean("x1"));
	assertFalse(lbf.containsBean("&x1"));
	assertFalse(lbf.isSingleton("x1"));
	assertFalse(lbf.isSingleton("&x1"));
	assertTrue(lbf.isPrototype("x1"));
	assertFalse(lbf.isPrototype("&x1"));
	assertTrue(lbf.isTypeMatch("x1", TestBean.class));
	assertFalse(lbf.isTypeMatch("&x1", TestBean.class));
	assertEquals(TestBean.class, lbf.getType("x1"));
	assertEquals(null, lbf.getType("&x1"));
	assertFalse(TestBeanFactory.initialized);
}
 
Example #19
Source File: InjectAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testObjectFactoryWithTypedMapMethod() throws Exception {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
	bpp.setBeanFactory(bf);
	bf.addBeanPostProcessor(bpp);
	bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryMapMethodInjectionBean.class));
	bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
	bf.setSerializationId("test");

	ObjectFactoryMapMethodInjectionBean bean = (ObjectFactoryMapMethodInjectionBean) bf.getBean("annotatedBean");
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	bean = (ObjectFactoryMapMethodInjectionBean) SerializationTestUtils.serializeAndDeserialize(bean);
	assertSame(bf.getBean("testBean"), bean.getTestBean());
	bf.destroySingletons();
}
 
Example #20
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigureBeanWithAutowiring() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	lbf.registerBeanDefinition("spouse", bd);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("age", "99");
	RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
	tbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_BY_NAME);
	lbf.registerBeanDefinition("test", tbd);
	TestBean tb = new TestBean();
	lbf.configureBean(tb, "test");
	assertSame(lbf, tb.getBeanFactory());
	TestBean spouse = (TestBean) lbf.getBean("spouse");
	assertEquals(spouse, tb.getSpouse());
}
 
Example #21
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpressionInStringArray() {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	BeanExpressionResolver beanExpressionResolver = mock(BeanExpressionResolver.class);
	when(beanExpressionResolver.evaluate(eq("#{foo}"), Matchers.any(BeanExpressionContext.class)))
			.thenReturn("classpath:/org/springframework/beans/factory/xml/util.properties");
	bf.setBeanExpressionResolver(beanExpressionResolver);

	RootBeanDefinition rbd = new RootBeanDefinition(PropertiesFactoryBean.class);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("locations", new String[]{"#{foo}"});
	rbd.setPropertyValues(pvs);
	bf.registerBeanDefinition("myProperties", rbd);
	Properties properties = (Properties) bf.getBean("myProperties");
	assertEquals("bar", properties.getProperty("foo"));
}
 
Example #22
Source File: CustomEditorConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	CustomEditorConfigurer cec = new CustomEditorConfigurer();
	Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<>();
	editors.put(Date.class, MyDateEditor.class);
	cec.setCustomEditors(editors);
	cec.postProcessBeanFactory(bf);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("date", "2.12.1975");
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	bf.registerBeanDefinition("tb", bd);

	TestBean tb = (TestBean) bf.getBean("tb");
	DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
	assertEquals(df.parse("2.12.1975"), tb.getDate());
}
 
Example #23
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testPrototypeCircleLeadsToException() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	Properties p = new Properties();
	p.setProperty("kerry.(class)", TestBean.class.getName());
	p.setProperty("kerry.(singleton)", "false");
	p.setProperty("kerry.age", "35");
	p.setProperty("kerry.spouse", "*rod");
	p.setProperty("rod.(class)", TestBean.class.getName());
	p.setProperty("rod.(singleton)", "false");
	p.setProperty("rod.age", "34");
	p.setProperty("rod.spouse", "*kerry");

	(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);
	try {
		lbf.getBean("kerry");
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
	}
}
 
Example #24
Source File: NestedBeansElementAttributeRecursionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void assertMerge(DefaultListableBeanFactory bf) {
	TestBean topLevel = bf.getBean("topLevelConcreteTestBean", TestBean.class);
	// has the concrete child bean values
	assertThat((Iterable<String>) topLevel.getSomeList(), hasItems("charlie", "delta"));
	// but does not merge the parent values
	assertThat((Iterable<String>) topLevel.getSomeList(), not(hasItems("alpha", "bravo")));

	TestBean firstLevel = bf.getBean("firstLevelNestedTestBean", TestBean.class);
	// merges all values
	assertThat((Iterable<String>) firstLevel.getSomeList(),
			hasItems("charlie", "delta", "echo", "foxtrot"));

	TestBean secondLevel = bf.getBean("secondLevelNestedTestBean", TestBean.class);
	// merges all values
	assertThat((Iterable<String>)secondLevel.getSomeList(),
			hasItems("charlie", "delta", "echo", "foxtrot", "golf", "hotel"));
}
 
Example #25
Source File: BusApplicationContext.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    XmlBeanDefinitionReader beanDefinitionReader =
        new ControlledValidationXmlBeanDefinitionReader(beanFactory);
    beanDefinitionReader.setNamespaceHandlerResolver(nsHandlerResolver);

    // Configure the bean definition reader with this context's
    // resource loading environment.
    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);
}
 
Example #26
Source File: ScopedProxyTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testProxyAssignable() throws Exception {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(bf).loadBeanDefinitions(MAP_CONTEXT);
	Object baseMap = bf.getBean("singletonMap");
	assertTrue(baseMap instanceof Map);
}
 
Example #27
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDestroyMethodOnInnerBean() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition innerBd = new RootBeanDefinition(BeanWithDestroyMethod.class);
	innerBd.setDestroyMethodName("close");
	RootBeanDefinition bd = new RootBeanDefinition(BeanWithDestroyMethod.class);
	bd.setDestroyMethodName("close");
	bd.getPropertyValues().add("inner", innerBd);
	lbf.registerBeanDefinition("test", bd);
	BeanWithDestroyMethod.closeCount = 0;
	lbf.preInstantiateSingletons();
	lbf.destroySingletons();
	assertEquals("Destroy methods invoked", 2, BeanWithDestroyMethod.closeCount);
}
 
Example #28
Source File: ImportSelectorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void importSelectors() {
	DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory());
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(beanFactory);
	context.register(Config.class);
	context.refresh();
	context.getBean(Config.class);
	InOrder ordered = inOrder(beanFactory);
	ordered.verify(beanFactory).registerBeanDefinition(eq("a"), any());
	ordered.verify(beanFactory).registerBeanDefinition(eq("b"), any());
	ordered.verify(beanFactory).registerBeanDefinition(eq("d"), any());
	ordered.verify(beanFactory).registerBeanDefinition(eq("c"), any());
}
 
Example #29
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testSingletonFactoryBeanIgnoredByNonEagerTypeMatching() {
	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");
	p.setProperty("x1.singleton", "true");
	(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);

	assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated());
	String[] beanNames = lbf.getBeanNamesForType(TestBean.class, true, false);
	assertEquals(0, beanNames.length);
	beanNames = lbf.getBeanNamesForAnnotation(SuppressWarnings.class);
	assertEquals(0, beanNames.length);

	assertFalse(lbf.containsSingleton("x1"));
	assertTrue(lbf.containsBean("x1"));
	assertTrue(lbf.containsBean("&x1"));
	assertFalse(lbf.isSingleton("x1"));
	assertFalse(lbf.isSingleton("&x1"));
	assertTrue(lbf.isPrototype("x1"));
	assertTrue(lbf.isPrototype("&x1"));
	assertTrue(lbf.isTypeMatch("x1", TestBean.class));
	assertFalse(lbf.isTypeMatch("&x1", TestBean.class));
	assertTrue(lbf.isTypeMatch("&x1", DummyFactory.class));
	assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClass(DummyFactory.class)));
	assertTrue(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)));
	assertFalse(lbf.isTypeMatch("&x1", ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)));
	assertEquals(TestBean.class, lbf.getType("x1"));
	assertEquals(DummyFactory.class, lbf.getType("&x1"));
	assertTrue("prototype not instantiated", !DummyFactory.wasPrototypeCreated());
}
 
Example #30
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testEmptyPropertiesPopulation() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	Properties p = new Properties();
	(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);
	assertTrue("No beans defined after ignorable invalid", lbf.getBeanDefinitionCount() == 0);
}