Spring Learning Summary Creating a bean with a static factory

Source: Internet
Author: User

When you create a bean, the class attribute must be specified, and this is the static factory class. FACTORY-METHOD Specifies the static factory method name.

Interface:

Public interface Being {public void testbeing ();}

Dog class

public class Dog implements Being{private string msg;public void Setmsg (String msg) {this.msg = msg;} @Overridepublic void Testbeing () {System.out.println (msg + "Dog Love Chew Bones");}}

Cat class

public class Cat implements Being{private string msg;public void Setmsg (String msg) {this.msg = msg;} @Overridepublic void Testbeing () {System.out.println (msg + "Cat loves eating Mice!");}}

 

In Bean Configuration

<?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-3.0.xsd "><bean id=" dog "class=" Com.springtest2.factory.BeingFactory "factory-method=" getbeing "><constructor-arg value=" dog "/>< Property Name= "MSG" value= "I am a dog"/></bean><bean id= "Cat" class= "Com.springtest2.factory.BeingFactory" Factory-method= "getbeing" ><constructor-arg value= "cat"/><property name= "msg" value= "I am a cat"/></ Bean></beans>

Call Test

private static void Testfactory () {ApplicationContext context = new Classpathxmlapplicationcontext (New string[]{"Beans_ Factory.xml "}); Being B1 = Context.getbean ("Dog", Being.class); b1.testbeing (); Being B2 = Context.getbean ("Cat", Being.class); b2.testbeing ();}

Output results

Spring Learning Summary Creating a bean with a static factory

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.