Profile:
The instance code specifically explains:
Folder structure
Car.java
Package Com.coslay.beans.factorybean;public class Car {private string brand;private double price;public string Getbrand ( ) {return brand;} public void Setbrand (String brand) {This.brand = brand;} Public double GetPrice () {return price;} public void Setprice (double price) {this.price = Price;} @Overridepublic String toString () {return "Car [brand=" + Brand + ", price=" + Price + "]";} Public Car () {System.out.println ("car ' s Constructor ..."); Public Car [String brand, double price] {super (); This.brand = Brand;this.price = Price;}}
Carfactorybean.java
Package Com.coslay.beans.factorybean;import org.springframework.beans.factory.factorybean;//own defined Factorybean need to be implemented Factorybean interface public class Carfactorybean implements Factorybean<car>{private String brand;public void Setbrand ( String brand) {This.brand = brand;} Returns the Bean object @overridepublic car GetObject () throws Exception {return new Car ("BMW", 5000000);} Returns the type of Bean @overridepublic class<?> getobjecttype () {return car.class;} @Overridepublic Boolean Issingleton () {return true;}}
Main.java
Package Com.coslay.beans.factorybean;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Main {public static void Main (String [] args) {ApplicationContext ctx = new Classpathxmlapplicationcontext ("Beans-beanfactory.xml"); Car car = (car) ctx.getbean ("Car"); SYSTEM.OUT.PRINTLN (car);}}
Beans-beanfactory.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 "><!-- Configure an instance of the Bean with Factorybean class: A full class name that points to Factorybean: Configure the properties of the Factorybean but the actual returned instance is Factorybean GetObject () The instance returned by the method--><bean id= "car" class= "Com.coslay.beans.factorybean.CarFactoryBean" ><property name= "brand" Value= "BMW" ></property></bean></beans>
Spring Factorybean Configuration Bean