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

Spring工厂方法创建(实例化)bean实例代码

程序员文章站 2023-12-18 17:06:22
目标明确 简单叙述一下本文想要解决的问题:如何在spring中不再使用spring创建bean实例,而是把bean创建过程转移到开发者手中。 思路清晰 创建bean实...

目标明确

简单叙述一下本文想要解决的问题:如何在spring中不再使用spring创建bean实例,而是把bean创建过程转移到开发者手中。

思路清晰

创建bean实例的方式:

1) 通过构造器(有参或无参)

方式: <bean id="" class=""/>

2) 通过静态工厂方法

方式: <bean id="" class="工厂类" factory-method="静态工厂方法"/>

注: 工厂类实例没有创建

3) 通过实例工厂方法(非静态方法)

方式:

<bean id="factory" class="工厂类"/>

<bean id="" factory-bean="factory" factory-method="实例工厂方法"/>

注: 工厂类实例被创建

方法实用

示例1

需求:

1 不想再bean.xml加载的时候实例化bean,而是想把加载bean.xml与实例化对象分离。

2 实现单例的bean

以上的情况,都可以通过工厂方法factory-method来创建bean。

这样再加载bean.xml时,不会直接实例化bean,而是当调用factory-method所指的方法时,才开始真正的实例化。

实现:通过spring的factory-method来创建单例的bean
  首先通过静态内部类创建一个单例对象

package com.spring.test.factorymethod;

public class stage {
  public void perform(){
    system.out.println("演出开始...");
  }
  private stage(){
    
  }
  private static class stagesingletonholder{
    static stage instance = new stage();
  }
  public static stage getinstance(){
    return stagesingletonholder.instance;
  }
}

在spring配置文件中指定加载的方法getinstance

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns="http://www.springframework.org/schema/beans"
  xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
   <bean id="thestage" class="com.spring.test.factorymethod.stage"
     factory-method="getinstance"></bean>
</beans>

通过应用上下文调用bean获取实例

package com.spring.test.factorymethod;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;

public class test {
  public static void main(string[] args) {
    applicationcontext ctx = new classpathxmlapplicationcontext("bean.xml");
    stage stage = ((stage)ctx.getbean("thestage"));//.getinstance();
    stage.perform();
  }
}

执行结果

一月 24, 2015 6:38:18 下午 org.springframework.context.support.abstractapplicationcontext preparerefresh
信息: refreshing org.springframework.context.support.classpathxmlapplicationcontext@512dbd1a: startup date [sat jan 24 18:38:18 cst 2015]; root of context hierarchy
一月 24, 2015 6:38:19 下午 org.springframework.beans.factory.xml.xmlbeandefinitionreader loadbeandefinitions
信息: loading xml bean definitions from class path resource [bean.xml]
一月 24, 2015 6:38:19 下午 org.springframework.beans.factory.support.defaultlistablebeanfactory preinstantiatesingletons
信息: pre-instantiating singletons in org.springframework.beans.factory.support.defaultlistablebeanfactory@2d1879ea: defining beans [duke,sonnet29,poeticduke,thestage]; root of factory hierarchy
演出开始...

工厂方法创建bean介绍

1. 使用静态工厂方法创建bean

使用静态工厂方法创建bean实例时,class属性也必须指定,但此时class属性并不是指定bean实例的实现类,而是静态工厂类。因为spring需要知道是用哪个工厂来创建bean实例。另外,还需要使用factory-method来指定静态工厂方法名,spring将调用静态工厂方法(可能包含一组参数),来返回一个bean实例,一旦获得了指定bean实例,spring后面的处理步骤与采用普通方法创建bean实例则完全一样。需要注意的是,当使用静态工厂方法来创建bean时,这个factory-method必须要是静态的。这段阐述听上去有点晕,话不多说,上代码:

先定义一个接口,静态方法产生的将是该接口的实例:

public interface animal {
  public void sayhello();
}

下面是接口的两个实现类:

public class cat implements animal {
  private string msg;
  //依赖注入时必须的setter方法
  public void setmsg(string msg){
    this.msg = msg;
  }
  @override
  public void sayhello(){
    system.out.println(msg + ",喵~喵~");
  }
}
 

public class dog implements animal {
  private string msg;
  //依赖注入时必须的setter方法
  public void setmsg(string msg){
    this.msg = msg;
  }
  @override
  public void sayhello(){
    system.out.println(msg + ",旺~旺~");
  }
}

下面的animalfactory工厂中包含了一个getanimal的静态方法,该方法将根据传入的参数决定创建哪个对象。这是典型的静态工厂设计模式。

public clas animalfactory {
  public static animal getanimal(string type){
    if ("cat".equalsignorecase(type)){
      return new cat();
    } else {
      return new dog();
    }
  }
}

如果需要指定spring使用animalfactory来产生animal对象,则可在spring配置文件中作如下配置:

<!-- 配置animalfactory的getanimal方法,使之产生cat -->
<bean id="cat" class="com.abc.animalfactory" factory-method="getanimal">
  <!-- 配置静态工厂方法的参数,getanimal方法将产生cat类型的对象 -->
  <constructor-arg value="cat" />
  <!-- 通过setter注入的普通属性 -->
  <property name="msg" value="猫猫" />
</bean>
<!-- 配置animalfactory的getanimal方法,使之产生dog -->
<bean id="dog" class="com.abc.animalfactory" factory-method="getanimal">
  <!-- 配置静态工厂方法的参数,getanimal方法将产生dog类型的对象 -->
  <constructor-arg value="dog" />
  <!-- 通过setter注入的普通属性 -->
  <property name="msg" value="狗狗" />
</bean>

从上面的配置可以看出:cat和dog两个bean配置的class和factory-method完全相同,这是因为两个实例都使用同一个静态工厂类、同一个静态工厂方法产生得到的。只是为这个静态工厂方法指定的参数不同,使用<constructor-arg />元素来为静态工厂方法指定参数。

主程序获取cat和dog两个bean实例的方法不变,同样只需要调用spring容器的getbean()即可:

public class test {
  public static void main(string args[]){
    applicationcontext context = 
        new classpathxmlapplicationcontext("applicationcontext.xml");
    animal a1 = context.getbean("cat", animal.class);
    a1.sayhello();
    animal a2 = context.getbean("dog", animal.class);
    a2.sayhello();
  }
}

输出结果:

<code class="hljs">猫猫,喵~喵~
狗狗,旺~旺~</code>

使用静态工厂方法创建实例时必须提供工厂类和产生实例的静态工厂方法。通过静态工厂方法创建实例时需要对spring配置文件做如下改变;

class属性不在是bean实例的实现类,而是生成bean实例的静态工厂类

使用factory-method指定生产bean实例的静态工厂方法

如果静态工厂方法需要参数,使用<constructor-arg />元素为其配置

当我们指定spring使用静态工厂方法来创建bean实例时,spring将先解析配置文件,并根据配置文件指定的信息,通过反射调用静态工厂类的静态工厂方法,并将该静态工厂方法的返回值作为bean实例,在这个过程中,spring不再负责创建bean实例,bean实例是由用户提供的静态工厂方法提供的。

2. 使用实例工厂方法创建bean

实例工厂方法与静态工厂方法只有一点不同:调用静态工厂方法只需要使用工厂类即可,调用实例工厂方法则必须使用工厂实例。所以在spring配置上也只有一点区别:配置静态工厂方法指定静态工厂类,配置实例工厂方法则指定工厂实例。同样是上面的例子将animalfactory修改为:

public clas animalfactory {
  public animal getanimal(string type){ //这里仅仅是去掉了static关键字
    if ("cat".equalsignorecase(type)){
      return new cat();
    } else {
      return new dog();
    }
  }
}

spring文件修改为:

<!-- 先配置工厂类 -->
<bean id="animalfactory" class="com.abc.animalfactory" />
<!-- 这里使用factory-bean指定实例工厂类对象 -->
<bean id="cat" factory-bean="animalfactory" factory-method="getanimal">
  <!-- 同样指定factory-method的参数 -->
  <constructor-arg value="cat" />
  <property name="msg" value="猫猫" />
</bean>

<bean id="dog" factory-bean="animalfactory" factory-method="getanimal">
  <constructor-arg value="dog" />
  <property name="msg" value="狗狗" />
</bean>

测试类不用修改,输出结果和上面相同。

很多情况下使用<bean id=”bean1” class=”…” />定义一个bean,这种定义方式spring将会调用默认的无参数构造方法创建bean实例。除此之外还可以使用工厂方式创建bean实例,实现bean创建与使用的分离,将bean创建工作交由工厂来完成。

配置工厂bean的三种方式。

抽象接口:

public interface imusicbox { 
   public void play(); 
} 

1、静态工厂方法取得bean实例

工厂类:

public class musicboxfactory { 
  public static imusicbox createmusicbox(){ 
  return new imusicbox(){ 
       public void play(){ 
    system.out.println("play piano..."); 
     } 
  }; 
  } 
} 

配置文件:

<bean id="musicbox" class="test.spring.musicboxfactory" factory-method="createmusicbox" /> 

测试类:

public static void main(string[] args) { 
  applicationcontext ctx =  
  new classpathxmlapplicationcontext("bean-config.xml"); 
  imusicbox musicbox = (imusicbox)ctx.getbean("musicbox"); 
  musicbox.play(); 
} 

2、工厂实例的方法取得bean实例

工厂类:

public class musicboxfactory { 
  public imusicbox createmusicbox(){//没有static修饰 
  return new imusicbox(){ 
       public void play(){ 
    system.out.println("play piano..."); 
     } 
  }; 
  } 
} 

配置文件:

<bean id="factorybean" class="test.spring.musicboxfactory" /> 
<bean id="musicbox" factory-bean="factorybean" factory-method="createmusicbox" /> 

“factory-bean”属性指定工厂bean,”factory-method”属性指定工厂方法来取得bean实例。

测试类:

public static void main(string[] args) { 
  applicationcontext ctx =  
  new classpathxmlapplicationcontext("bean-config.xml"); 
  imusicbox musicbox = (imusicbox)ctx.getbean("musicbox"); 
  musicbox.play(); 
} 

3、工厂类实现org.springframework.beans.factory.facotrybean接口

工厂类:

import org.springframework.beans.factory.factorybean; 
 
public class musicboxfactory2 implements factorybean { 
  public object getobject() throws exception { 
  return new imusicbox(){ 
    public void play(){ 
       system.out.println("play piano..."); 
       } 
  }; 
  } 
 
  public class getobjecttype() { 
  return imusicbox.class; 
  } 
 
  public boolean issingleton() { 
  return false; 
  } 
} 

配置文件:

<bean id="musicbox" class="test.spring.musicboxfactory2"/> 

测试类:

public static void main(string[] args) { 
  applicationcontext ctx =  
  new classpathxmlapplicationcontext("bean-config.xml"); 
  //不加 & 返回工厂的“产品” 
  imusicbox musicbox = (imusicbox)ctx.getbean("musicbox"); 
  musicbox.play(); 
  //加 & 返回工厂类实例 
  object obj = ctx.getbean("&musicbox");  
  system.out.println(obj.getclass().getname());  
 
} 

实现factorybean接口的类不会被视为普通的bean,spring会自动检测,调用getobject方法获取bean实例

总结

spring工厂方法实例化bean实例的介绍就到这里,有什么不足之处,大家可以留言指出。感谢朋友们对本站的支持!

上一篇:

下一篇: