整个项目文件夹如图:
1. 创建三个类,分别是BeanClass类,BeanInstanceFactory类,BeanStaticFactory类分别用于构造方法,实例工厂实例化和静态工厂实例化Bean。
<1>构造方法实例化:在项目的src文件夹下创建包instance,并在内创建BeanClass类:
package instance;
public class BeanClass {
public String message;
public BeanClass()
{
message="构造方法实例化bean";
}
public BeanClass(String s)
{
message=s;
}
}
<2>实例工厂实例化: 在项目的src文件夹下的包instance内创建BeanInstanceFactory类
package instance;
public class BeanInstanceFactory {
public BeanClass createBeanClassInstance() {
return new BeanClass("调用实例工厂方法实例化Bean");
}
}
<3>静态工厂实例化: 在项目的src文件夹下的包instance内创建BeanStaticFactory类
package instance;
public class BeanStaticFactory {
private static BeanClass beanInstance=new BeanClass("调用静态工厂实例化Bean");
public static BeanClass createInstance() {
return beanInstance;
}
}
2.在项目的src文件夹下创建配置文件applicationContext.xml
<?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">
<!--id声明获取Bean的来源,class声明工作运行类-->
<!-- 构造方法实例化Bean -->
<bean id="constructorInstance" class="instance.BeanClass"></bean>
<!-- 静态工厂方法实例化Bean.createInstance为静态工厂类BeanStaticFactory中的静态方法 -->
<bean id="staticFactoryInstance" class="instance.BeanStaticFactory" factory-method="createInstance"></bean>
<!-- 配置工厂 -->
<bean id="myFactory" class="instance.BeanInstanceFactory"></bean>
<!-- 使用factory-bean的属性指定配置工厂,使用factory-method属性指定使用工厂中哪个方法实例化Bean -->
<bean id="instanceFactoryInstance" factory-bean="myFactory" factory-method="createBeanClassInstance"></bean>
</beans>
3.在项目src文件夹下创建包test,并在文件夹下创建测试类TestInstance
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import instance.BeanClass;
//测试类
public class TestInstance {
public static void main(String[] args) {
// TODO Auto-generated method stub
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext appCon=new ClassPathXmlApplicationContext("applicationContext.xml");
//测试构造方法实例化Bean
BeanClass b1=(BeanClass)appCon.getBean("constructorInstance");
System.out.println(b1+b1.message);
//测试静态工厂方法实例化Bean
BeanClass b2=(BeanClass)appCon.getBean("staticFactoryInstance");
System.out.println(b2+b2.message);
//测试实例工厂方法实例化Bean
BeanClass b3=(BeanClass)appCon.getBean("instanceFactoryInstance");
System.out.println(b3+b3.message);
}
}
运行结果如下: