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.
可打印的.java
package com.javatpoint;
public interface Printable {
void print();
}
爪哇
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
}
}
应用程序上下文.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="pfactory" class="com.javatpoint.PrintableFactory"></bean>
<bean id="p" class="com.javatpoint.Printable" factory-method="getPrintable"
factory-bean="pfactory"></bean>
</beans>
注意public Printable getPrintable()
ofPrintableFactory.java
是一个非静态方法。通常,如果我们想要访问/调用类的方法或其他资源,我们必须创建它的实例。同样,我们创建了它 bean。使用 bean 的引用变量pfactory
,我们调用工厂方法getPrintable
。