欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Bean的实例化(Spring)

程序员文章站 2022-03-03 11:18:12
...

1.构造器实例化

Spring容器通过Bean对应的类中默认的构造函数来实例化bean

<bean id="bean1" class="com.instance.contructor.Bean1"></bean>

2.静态工厂方式实例化

创建一个静态工厂来实例化Bean

Bean

package com.instance.static_factory;

public class Bean2 {

}

静态工厂创建示例

package com.instance.static_factory;

public class MyBean2Factory {

	public static Bean2 createBean() {
		return new Bean2();
	}
}

配置文件示例

需要在bean标签中设置factory-method属性的值,只需写上静态工厂类中创建Bean的静态方法名称即可。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="bean2" class="com.instance.static_factory.MyBean2Factory" factory-method="createBean"></bean>
</beans>

 

3.实例工厂方式实例化

在配置文件中,通过factory-bean属性配置一个实例工厂,然后使用factory-method属性确定使用工厂中的哪个方法。

Bean:

package com.instance.factory;

public class Bean3 {

}

实例工厂类:

package com.instance.factory;

public class MyBean3Factory {

	public MyBean3Factory() {
		System.out.println("Bean3工厂实例化中...");
	}
	
	public Bean3 createBean() {
		return new Bean3();
	}
}

配置文件示例:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="myBean3Factory" class="com.instance.factory.MyBean3Factory"></bean>
	<bean id="bean3" factory-bean="myBean3Factory" factory-method="createBean"></bean>
</beans>

测试代码:

package com.instance.static_factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InstanceTest2 {
	public static void main(String[] args) {
		//定义配置文件路径
		String xmlPath = "com/instance/static_factory/bean2.xml";
		//创建applicationContext对象
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		//获取Bean2的实例并输出
		System.out.println(applicationContext.getBean("bean2"));
	}

}