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

The following examples show how to use org.springframework.beans.factory.support.DefaultListableBeanFactory. These examples are extracted from open source projects. 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
@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 2
@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 3
@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 4
@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 5
@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
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 7
@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 8
Source Project: java-technology-stack   Source File: ProxyFactoryBeanTests.java    License: 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 9
@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 10
Source Project: java-technology-stack   Source File: BeanConfigurerSupportTests.java    License: 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 11
Source Project: spring-analysis-note   Source File: AutowireWithExclusionTests.java    License: 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 12
Source Project: spring-analysis-note   Source File: FactoryMethodTests.java    License: 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 13
Source Project: cxf   Source File: BusApplicationContext.java    License: 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 14
@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 15
@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 16
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 17
@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 18
Source Project: spring-analysis-note   Source File: CustomEditorConfigurerTests.java    License: 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 19
@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 20
@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
@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 22
@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 23
Source Project: spring-analysis-note   Source File: XmlBeanFactoryTests.java    License: 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 24
Source Project: java-technology-stack   Source File: XmlBeanFactoryTests.java    License: 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 25
@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 26
Source Project: spring-analysis-note   Source File: XmlBeanFactoryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomStringConstructor() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
	AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("stringConstructor");
	bd.setLenientConstructorResolution(false);
	StringConstructorTestBean tb = (StringConstructorTestBean) xbf.getBean("stringConstructor");
	assertEquals("test", tb.name);
}
 
Example 27
Source Project: java-technology-stack   Source File: FactoryMethodTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCanSpecifyFactoryMethodArgumentsOnSingleton() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

	// First getBean call triggers actual creation of the singleton bean
	TestBean tb = new TestBean();
	FactoryMethods fm1 = (FactoryMethods) xbf.getBean("testBeanOnly", tb);
	assertSame(tb, fm1.getTestBean());
	FactoryMethods fm2 = (FactoryMethods) xbf.getBean("testBeanOnly", new TestBean());
	assertSame(fm1, fm2);
	assertSame(tb, fm2.getTestBean());
}
 
Example 28
Source Project: spring-analysis-note   Source File: ProxyFactoryBeanTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testDetectsInterfaces() throws Exception {
	ProxyFactoryBean fb = new ProxyFactoryBean();
	fb.setTarget(new TestBean());
	fb.addAdvice(new DebugInterceptor());
	fb.setBeanFactory(new DefaultListableBeanFactory());
	ITestBean proxy = (ITestBean) fb.getObject();
	assertTrue(AopUtils.isJdkDynamicProxy(proxy));
}
 
Example 29
Source Project: spring4-understanding   Source File: ImportTests.java    License: Apache License 2.0 5 votes vote down vote up
private DefaultListableBeanFactory processConfigurationClasses(Class<?>... classes) {
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	for (Class<?> clazz : classes) {
		beanFactory.registerBeanDefinition(clazz.getSimpleName(), new RootBeanDefinition(clazz));
	}
	ConfigurationClassPostProcessor pp = new ConfigurationClassPostProcessor();
	pp.postProcessBeanFactory(beanFactory);
	return beanFactory;
}
 
Example 30
Source Project: java-technology-stack   Source File: ImportSelectorTests.java    License: 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());
}