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

The following examples show how to use org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons() . 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: MBeanExporterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWildcardCanBeUsedInNotificationListenersMap() throws Exception {
	String beanName = "charlesDexterWard";
	BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class);

	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	factory.registerBeanDefinition(beanName, testBean.getBeanDefinition());
	factory.preInstantiateSingletons();
	Object testBeanInstance = factory.getBean(beanName);

	MBeanExporter exporter = new MBeanExporter();
	exporter.setServer(getServer());
	Map<String, Object> beansToExport = new HashMap<>();
	beansToExport.put("test:what=ever", testBeanInstance);
	exporter.setBeans(beansToExport);
	exporter.setBeanFactory(factory);
	StubNotificationListener listener = new StubNotificationListener();
	exporter.setNotificationListenerMappings(Collections.singletonMap("*", listener));

	start(exporter);
}
 
Example 2
Source File: RequiredAnnotationBeanPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithCustomAnnotation() {
	try {
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.getBeanDefinition();
		factory.registerBeanDefinition("testBean", beanDef);
		RequiredAnnotationBeanPostProcessor rabpp = new RequiredAnnotationBeanPostProcessor();
		rabpp.setRequiredAnnotationType(MyRequired.class);
		factory.addBeanPostProcessor(rabpp);
		factory.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		String message = ex.getCause().getMessage();
		assertTrue(message.contains("Property"));
		assertTrue(message.contains("name"));
		assertTrue(message.contains("testBean"));
	}
}
 
Example 3
Source File: AutowireWithExclusionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void byTypeAutowireWithPrimaryOverridingParentFactory() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	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 4
Source File: FactoryMethodTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testFactoryMethodWithDifferentReturnType() {
	DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
	reader.loadBeanDefinitions(new ClassPathResource("factory-methods.xml", getClass()));

	// Check that listInstance is not considered a bean of type FactoryMethods.
	assertTrue(List.class.isAssignableFrom(xbf.getType("listInstance")));
	String[] names = xbf.getBeanNamesForType(FactoryMethods.class);
	assertTrue(!Arrays.asList(names).contains("listInstance"));
	names = xbf.getBeanNamesForType(List.class);
	assertTrue(Arrays.asList(names).contains("listInstance"));

	xbf.preInstantiateSingletons();
	assertTrue(List.class.isAssignableFrom(xbf.getType("listInstance")));
	names = xbf.getBeanNamesForType(FactoryMethods.class);
	assertTrue(!Arrays.asList(names).contains("listInstance"));
	names = xbf.getBeanNamesForType(List.class);
	assertTrue(Arrays.asList(names).contains("listInstance"));
	List<?> list = (List<?>) xbf.getBean("listInstance");
	assertEquals(Collections.EMPTY_LIST, list);
}
 
Example 5
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testDependsOnCycle() {
	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("tb1");
	lbf.registerBeanDefinition("tb2", bd2);
	try {
		lbf.preInstantiateSingletons();
		fail("Should have thrown BeanCreationException");
	}
	catch (BeanCreationException ex) {
		// expected
		assertTrue(ex.getMessage().contains("Circular"));
		assertTrue(ex.getMessage().contains("'tb2'"));
		assertTrue(ex.getMessage().contains("'tb1'"));
	}
}
 
Example 6
Source File: AmazonWebserviceClientConfigurationUtilsTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void registerAmazonWebserviceClient_withCustomRegionConfiguration_returnsBeanDefinitionWithRegionConfigured()
		throws Exception {
	// Arrange
	DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
	beanFactory.registerSingleton(
			AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
			new StaticAwsCredentialsProvider());

	BeanDefinitionHolder beanDefinitionHolder = AmazonWebserviceClientConfigurationUtils
			.registerAmazonWebserviceClient(new Object(), beanFactory,
					AmazonTestWebserviceClient.class.getName(), null,
					Regions.EU_WEST_1.getName());

	// Act
	beanFactory.preInstantiateSingletons();
	AmazonTestWebserviceClient client = beanFactory.getBean(
			beanDefinitionHolder.getBeanName(), AmazonTestWebserviceClient.class);

	// Assert
	assertThat(client).isNotNull();
	assertThat(beanDefinitionHolder.getBeanName()).isEqualTo("amazonTestWebservice");
	assertThat(client.getRegion()).isEqualTo(Region.getRegion(Regions.EU_WEST_1));
}
 
Example 7
Source File: XmlBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAbstractParentBeans() {
	DefaultListableBeanFactory parent = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT);
	parent.preInstantiateSingletons();
	assertTrue(parent.isSingleton("inheritedTestBeanWithoutClass"));

	// abstract beans should not match
	Map<?, ?> tbs = parent.getBeansOfType(TestBean.class);
	assertEquals(2, tbs.size());
	assertTrue(tbs.containsKey("inheritedTestBeanPrototype"));
	assertTrue(tbs.containsKey("inheritedTestBeanSingleton"));

	// abstract bean should throw exception on creation attempt
	try {
		parent.getBean("inheritedTestBeanWithoutClass");
		fail("Should have thrown BeanIsAbstractException");
	}
	catch (BeanIsAbstractException ex) {
		// expected
	}

	// non-abstract bean should work, even if it serves as parent
	assertTrue(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean);
}
 
Example 8
Source File: RequiredAnnotationBeanPostProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithStaticFactoryMethodAndRequiredPropertiesSpecified() {
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	BeanDefinition beanDef = BeanDefinitionBuilder
			.genericBeanDefinition(RequiredTestBean.class)
			.setFactoryMethod("create")
			.addPropertyValue("age", "24")
			.addPropertyValue("favouriteColour", "Blue")
			.addPropertyValue("jobTitle", "Grand Poobah")
			.getBeanDefinition();
	factory.registerBeanDefinition("testBean", beanDef);
	factory.addBeanPostProcessor(new RequiredAnnotationBeanPostProcessor());
	factory.preInstantiateSingletons();
	RequiredTestBean bean = (RequiredTestBean) factory.getBean("testBean");
	assertEquals(24, bean.getAge());
	assertEquals("Blue", bean.getFavouriteColour());
}
 
Example 9
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBeanDefinitionRemoval() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	lbf.setAllowBeanDefinitionOverriding(false);
	lbf.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class));
	lbf.registerAlias("test", "test2");
	lbf.preInstantiateSingletons();
	lbf.removeBeanDefinition("test");
	lbf.removeAlias("test2");
	lbf.registerBeanDefinition("test", new RootBeanDefinition(NestedTestBean.class));
	lbf.registerAlias("test", "test2");
	assertTrue(lbf.getBean("test") instanceof NestedTestBean);
	assertTrue(lbf.getBean("test2") instanceof NestedTestBean);
}
 
Example 10
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterExistingSingletonWithNameOverriding() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	Properties p = new Properties();
	p.setProperty("test.(class)", TestBean.class.getName());
	p.setProperty("test.name", "Tony");
	p.setProperty("test.age", "48");
	p.setProperty("test.spouse(ref)", "singletonObject");
	(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);
	lbf.registerBeanDefinition("singletonObject", new RootBeanDefinition(PropertiesFactoryBean.class));
	Object singletonObject = new TestBean();
	lbf.registerSingleton("singletonObject", singletonObject);
	lbf.preInstantiateSingletons();

	assertTrue(lbf.isSingleton("singletonObject"));
	assertEquals(TestBean.class, lbf.getType("singletonObject"));
	TestBean test = (TestBean) lbf.getBean("test");
	assertEquals(singletonObject, lbf.getBean("singletonObject"));
	assertEquals(singletonObject, test.getSpouse());

	Map<?, ?>  beansOfType = lbf.getBeansOfType(TestBean.class, false, true);
	assertEquals(2, beansOfType.size());
	assertTrue(beansOfType.containsValue(test));
	assertTrue(beansOfType.containsValue(singletonObject));

	beansOfType = lbf.getBeansOfType(null, false, true);

	Iterator<String> beanNames = lbf.getBeanNamesIterator();
	assertEquals("test", beanNames.next());
	assertEquals("singletonObject", beanNames.next());
	assertFalse(beanNames.hasNext());
	assertEquals(2, beansOfType.size());

	assertTrue(lbf.containsSingleton("test"));
	assertTrue(lbf.containsSingleton("singletonObject"));
	assertTrue(lbf.containsBeanDefinition("test"));
	assertTrue(lbf.containsBeanDefinition("singletonObject"));
}
 
Example 11
Source File: DefaultListableBeanFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDestroyMethodOnInnerBeanAsPrototype() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition innerBd = new RootBeanDefinition(BeanWithDestroyMethod.class);
	innerBd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
	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", 1, BeanWithDestroyMethod.closeCount);
}
 
Example 12
Source File: AutowireWithExclusionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void byTypeAutowireWithExclusionInParentFactory() throws Exception {
	CountingFactory.reset();
	DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml");
	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);
	TestBean rob = (TestBean) child.getBean("rob2");
	assertEquals("props1", rob.getSomeProperties().getProperty("name"));
	assertEquals(1, CountingFactory.getFactoryBeanInstanceCount());
}
 
Example 13
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircularReferenceThroughAutowiring() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyBean.class);
	bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	lbf.registerBeanDefinition("test", bd);
	try {
		lbf.preInstantiateSingletons();
		fail("Should have thrown UnsatisfiedDependencyException");
	}
	catch (UnsatisfiedDependencyException expected) {
	}
}
 
Example 14
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 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 15
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testUnreferencedSingletonWasInstantiated() {
	KnowsIfInstantiated.clearInstantiationRecord();
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	Properties p = new Properties();
	p.setProperty("x1.(class)", KnowsIfInstantiated.class.getName());
	assertTrue("singleton not instantiated", !KnowsIfInstantiated.wasInstantiated());
	(new PropertiesBeanDefinitionReader(lbf)).registerBeanDefinitions(p);
	lbf.preInstantiateSingletons();
	assertTrue("singleton was instantiated", KnowsIfInstantiated.wasInstantiated());
}
 
Example 16
Source File: DefaultLifecycleMethodsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void ignoreDefaultLifecycleMethods() throws Exception {
	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource(
			"ignoreDefaultLifecycleMethods.xml", getClass()));
	bf.preInstantiateSingletons();
	bf.destroySingletons();
}
 
Example 17
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 18
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testAvoidCircularReferenceThroughAutowiring() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	RootBeanDefinition bd = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
	bd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	lbf.registerBeanDefinition("test", bd);
	RootBeanDefinition bd2 = new RootBeanDefinition(String.class);
	bd2.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
	lbf.registerBeanDefinition("string", bd2);
	lbf.preInstantiateSingletons();
}
 
Example 19
Source File: BeanLifecycleDemo.java    From geekbang-lessons with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    // 添加 BeanPostProcessor 实现 MyInstantiationAwareBeanPostProcessor
    beanFactory.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
    // 添加 MyDestructionAwareBeanPostProcessor 执行销毁前回调
    beanFactory.addBeanPostProcessor(new MyDestructionAwareBeanPostProcessor());
    // 添加 CommonAnnotationBeanPostProcessor 解决 @PostConstruct @PreDestroy
    beanFactory.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());

    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    String[] locations = {"META-INF/dependency-lookup-context.xml", "META-INF/bean-constructor-dependency-injection.xml"};
    int beanNumbers = beanDefinitionReader.loadBeanDefinitions(locations);
    System.out.println("已加载 BeanDefinition 数量:" + beanNumbers);
    // 显示地执行 preInstantiateSingletons()
    // SmartInitializingSingleton 通常在 Spring ApplicationContext 场景使用
    // preInstantiateSingletons 将已注册的 BeanDefinition 初始化成 Spring Bean
    beanFactory.preInstantiateSingletons();

    // 通过 Bean Id 和类型进行依赖查找
    User user = beanFactory.getBean("user", User.class);
    System.out.println(user);

    User superUser = beanFactory.getBean("superUser", User.class);
    System.out.println(superUser);

    // 构造器注入按照类型注入,resolveDependency
    UserHolder userHolder = beanFactory.getBean("userHolder", UserHolder.class);

    System.out.println(userHolder);

    // 执行 Bean 销毁(容器内)
    beanFactory.destroyBean("userHolder", userHolder);
    // Bean 销毁并不意味着 Bean 垃圾回收了
    System.out.println(userHolder);

    // 销毁 BeanFactory 中的单例 Bean
    beanFactory.destroySingletons();
    // 强制 GC
    System.gc();
    // 等待一段时间
    Thread.sleep(1000L);
    // 强制 GC
    System.gc();
}
 
Example 20
Source File: XmlBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testCollectionsReferredToAsRefLocals() throws Exception {
	DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
	new XmlBeanDefinitionReader(factory).loadBeanDefinitions(COLLECTIONS_XSD_CONTEXT);
	factory.preInstantiateSingletons();
}