Chinaunix首页 | 论坛 | 博客
  • 博客访问: 382331
  • 博文数量: 80
  • 博客积分: 2682
  • 博客等级: 少校
  • 技术积分: 907
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-16 09:55
文章分类

全部博文(80)

文章存档

2012年(80)

分类: 系统运维

2012-12-12 15:55:37

 第一种    静态方法  
    applicationContext.xml                                               指定生产类的方法  ( static)  
  cat"   class="com.baidu."   factory-method="getInstance" >   
     注意:  通过 id   cat  得到是  生产出来的   Dog 对象
   JAVA  代码
    public class Cat {
public static Dog getInstance() {         // 必须是 静态方法
return new Dog();          //  new  出来的Dog
}
    }
  
   public class Dog {
public Dog() {
System.out.println("I'm a Dog");
}
   }

   第二种    非静态方法     
     applicationContext.xml
         spring 自动 进行 String 到 Class 的类型转换
       com.baidu.">     set  注入   要生产的类的全名
         
     id="dog"    factory-bean="cat"    factory-method="getInstance"> //  通过  id  dog  得到 Dog对象

  public class Cat {
private Class classType  ;       //   Class   类型 

public void setClassType(Class classType) {
this.classType = classType;
}

private Dog getInstance() throws Exception{
return (Dog)classType.newInstance();       //   反射机制
}
   }
   
  第三种 方式  实现   FactoryBean  接口 
     延迟加载  在调用  getBean  时 才实例化对象 (前两种方法 applicationContext 实例化时  就 实例化 bean 对象 
     
          
     通过id  cat   得到是 Dog对象      Dog dog = (Dog)applicationCotext.getBean("cat");     
   
  import org.springframework.beans.factory.FactoryBean;
    
   public class Cat implements FactoryBean  {
private Class classType;

public void setClassType(Class classType) {
this.classType = classType;
}

public Object getObject() throws Exception {
return classType.newInstance();
}

public Class getObjectType() {
return classType;
}

public boolean isSingleton() {
return false;
}

     }  
阅读(819) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~