What is the difference between spring factory-method and factory-bean?

前端 未结 6 2028
小鲜肉
小鲜肉 2021-02-02 10:28

I am new Springs. In Bean tag I found factory-method and factory-bean Attributes. What is the difference between factory-method and factory-bean?

I am using factory-meth

6条回答
  •  醉梦人生
    2021-02-02 10:46

    factory-method: represents the factory method that will be invoked to inject the bean.
    factory-bean: represents the reference of the bean by which factory method will be invoked. It is used if factory method is non-static.
    

    Printable.java

    package com.javatpoint;  
    public interface Printable {  
        void print();  
    }  
    

    A.java

    package com.javatpoint;  
    public class A implements Printable{  
        @Override  
        public void print() {  
            System.out.println("hello a");  
        }      
    } 
    

    B.java

    package com.javatpoint;  
    public class B implements Printable{  
        @Override  
        public void print() {  
            System.out.println("hello b");  
        }  
    }  
    

    PrintableFactory.java

    package com.javatpoint;  
    public class PrintableFactory {  
        //non-static factory method  
        public Printable getPrintable(){  
            return new A();//return any one instance, either A or B  
        }  
    }  
    

    applicationContext.xml

      
      
    
      
      
    
      
    

    Notice that public Printable getPrintable() of PrintableFactory.java is a non-static method. Generally if we want access/call method or other resources of the a class we have to create it's instance. Similarly in that we created it bean. using bean's reference variable pfactory we are calling the factory method getPrintable.

提交回复
热议问题