Spring (13): Two ways to configure a bean using a factory method (static factory method & Instance factory method)

Source: Internet
Author: User
Tags instance method

To create a bean by calling the static factory method

1) Calling the static factory method to create the bean is the process of encapsulating the object creation into a static method. When a client needs an object, it simply calls the static method without having to worry about the specifics of the object being created.

2) to declare a bean created through a static method, you need to specify the class of the method that owns the factory in the Bean's class attribute, and you need to specify the name of the factory method in the bean's Factory-method attribute. Finally, use the <constructor-arg> element to pass method parameters for the method.

Example:

First step: Create a Java project and import the package:

Step Two: Create Com.dx.spring.beans.factory.car.java,com.dx.spring.beans.factory.staticcarfactory.java,bean-factory.xml:

Car.java

 Packagecom.dx.spring.beans.factory; Public classCar {PrivateString brand; Private DoublePrice ;  PublicCar () {} PublicCar (String brand,DoublePrice ) {        Super();  This. Brand =brand;  This. Price =Price ; }     PublicString Getbrand () {returnbrand; }     Public voidSetbrand (String brand) { This. Brand =brand; }     Public DoubleGetPrice () {returnPrice ; }     Public voidSetprice (DoublePrice ) {         This. Price =Price ; } @Override PublicString toString () {return"Car [brand=" + Brand + ", price=" + Price + "]"; }    }
View Code

Staticcarfactory.java

 Packagecom.dx.spring.beans.factory;ImportJava.util.HashMap;ImportJava.util.Map; Public classStaticcarfactory {Private StaticMap<string, car> cars =NULL; Static{Cars=NewHashmap<>(); Cars.put ("Audi",NewCar ("AUDI", 350000)); Cars.put ("Ford",NewCar ("FORD", 200000)); }     Public StaticCar Getcar (String key) {returnCars.get (key); }}

Bean-factory.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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" >    <BeanID= "Car1"class= "Com.dx.spring.beans.factory.StaticCarFactory"Factory-method= "Getcar">        <Constructor-argname= "Key"value= "Audi"></Constructor-arg>    </Bean></Beans>

Step three: Add the Client.java test class and execute the test:

 Packagecom.dx.spring.beans.factory;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classClient { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean-factory.xml"); Car car1= (Car) ctx.getbean ("Car1");    System.out.println (CAR1); }}

The results of the execution were successfully returned CAR1:

Car [Brand=audi, price=350000.0]

To create a bean by invoking an instance factory method

1) Example ICBC method: The object creation process is encapsulated in another object instance of the method, when the client needs to request the object, only need to simply call the instance method without the need to care about the object's creation details.

2) You need to declare the bean created by the instance factory method:

----Specify the bean that owns the factory method in the bean's Factory-bean attribute;

----Specify the name of the factory method in the Factory-method attribute;

----Use the <constructor-arg> element to pass method parameters for the factory method.

Example: (Note: modified based on the example above)

First step: Create Com.dx.spring.beans.factory.InstanceCarFactory.java

 Packagecom.dx.spring.beans.factory;ImportJava.util.HashMap;ImportJava.util.Map; Public classInstancecarfactory {PrivateMap<string, car> cars =NULL;  Publicinstancecarfactory () {Cars=NewHashmap<>(); Cars.put ("Audi",NewCar ("Audi", 350000)); Cars.put ("Ford",NewCar ("Ford", 200000)); }     PublicCar Getcar (String key) {returnCars.get (key); }}

Step Two: Add the following configuration in the Bean-factory.xml (Spring bean configuration file):

    <BeanID= "Instancecarfactory"class= "Com.dx.spring.beans.factory.InstanceCarFactory"></Bean>    <BeanID= "Car2"Factory-bean= "Instancecarfactory"Factory-method= "Getcar">        <Constructor-argname= "Key"value= "Ford"></Constructor-arg>    </Bean>

Step three: Modify Client.java, add CAR2 test:

 Packagecom.dx.spring.beans.factory;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classClient { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean-factory.xml"); Car car1= (Car) ctx.getbean ("Car1");                System.out.println (CAR1); Car car2= (Car) ctx.getbean ("Car2");    System.out.println (CAR2); }}

The test results are:

Car [Brand=audi, price=350000.0]
Car [Brand=ford, price=200000.0]

Spring (13): Two ways to configure a bean using a factory method (static factory method & Instance factory method)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.