Three ways to create objects "Spring"

Source: Internet
Author: User

The construction of spring can be found in the following: Analysis of the spring framework. Before testing, you should configure your environment to bring in the relevant jar packages. The objects that spring creates are singleton patterns by default, unless specified by scope.

First, create an object from a constructor function. 2.1 Injecting values using the +setter method of the parameterless constructor

The most basic method of object creation, only need to have a parameterless constructor (the class does not write any constructors, the default is that there is a constructor, if you write any one constructor, the default parameterless constructor will not be created automatically Oh!! ) and the setter method for the field.

Person class:

PackageCom.mc.base.learn.spring.bean;PublicClassperson {PrivateString name;PrivateInteger ID;PublicString GetName () {return name; public void SetName ( String name {this.name = name;} public Integer GetId () {return ID; } public void SetId ( Integer ID) {this.id = ID;} @Override public String toString () {return "person [name=" + name + ", id=" + ID + "]"          

XML configuration:

<?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"><BeanClass= "Com.mc.base.learn.spring.bean.Person"Id= "Person"><property name= "name" Span style= "color: #ff0000;" > Value= "Liuchunfu" ></ property> << Span style= "color: #800000;" >property name= "id"  Value= "></> </> </beans< Span style= "color: #0000ff;" >>                 

Its essence is:

Springcontext uses the parameterless constructor to create an object and then assigns a value using the Setter method. So if the parameterless constructor does not exist, the spring context creates an error when the object is created.



Nested exception is Java.lang.NoSuchMethodException:com.mc.base.learn.spring.bean.Person. <init>() at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean ( abstractautowirecapablebeanfactory.java:1105) .....
2.2 Direct injection using a parametric constructor

Person class:

PackageCom.mc.base.learn.spring.bean;PublicClassperson {PrivateString name;PrivateInteger ID;PublicPerson (String name, Integer ID) {Super();THIS.name =NameThis.id =Id }PublicString GetName () {return name; public void SetName ( String name {this.name = name;} public Integer GetId () {return ID; } public void SetId ( Integer ID) {this.id = ID;} @Override public String toString () {return "person [name=" + name + ", id=" + ID + "]"          

XML configuration:

<?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"><BeanClass= "Com.mc.base.learn.spring.bean.Person"Id= "Person"><Constructor-argname= "id"  Value= "123" ></constructor-arg > <name= "name"  Value=" Liuchunfu " ></constructor-arg> </bean> </beans>       
Second, create objects by static Factory mode.

The object of a static factory is created when the container is loaded.

PackageCom.mc.base.learn.spring.factory;ImportCom.mc.base.learn.spring.bean.Person;PublicClasspersonstaticfactory {PublicStaticPerson Createperson () {ReturnNewPerson (); }/** * Factory method with parameters how do I handle it? * @Title: Createperson * @Description: TODO (here is a word describing the effect of this method) *  @param  @param  ID *  @param @ Param name *  @param @ Return *  @return  person return type *  @throws */public staticreturn new person (name,id);}     
    <!--The core of the static factory method is Class+factory-method-
<bean id= "person" class= " Com.mc.base.learn.spring.factory.PersonStaticFactory " factory-method=" Createperson ">
<!-- Pass parameters to Createperson by property method --
<property name= "name" value= "Liuchunfu" ></property>
<property name= "id" value= "></property>"
</bean>

The test is as follows:

    @Test    publicvoidthrows  Exception {        ApplicationContext ac =new classpathxmlapplicationcontext ("Applicationcontext.xml");        Person Person =ac.getbean (' person3 ', person.  Class);        SYSTEM.OUT.PRINTLN (person); // Person [Name=liuchunfu, id=125]    }
Third, the object is created through the instance factory method.

The instance factory invokes the object through an instance, but the resulting object is ultimately the simple interest pattern. The object created by the instance factory and the static factory is a singleton pattern, and the difference is that the actual creation of the object is different, the static factory is created when the container is created, and the instance factory is created when the method is called. Readers who know the singleton pattern design (a hungry man and lazy) in the Java design pattern must be aware of the static factory pattern and instance factory pattern here.

Package com.mc.base.learn.spring.factory;  Import Com.mc.base.learn.spring.bean.Person;  Classpublicnew Person ();}}      
    <BeanID= "Personfactory"class= "Cn.test.util.PresonFactoryInstance"></Bean>    <BeanID= "Person4"Factory-bean= "Personfactory"Factory-method= "Createperson">        < Propertyname= "Name"value= "Liuchunfu"></ Property>        < Propertyname= "id"value= " the"></ Property>    </Bean>
    @Test    publicvoidthrows  Exception {        ApplicationContext ac =new classpathxmlapplicationcontext ("Applicationcontext.xml");        Person Person =ac.getbean (' person4 ', person.  Class);        SYSTEM.OUT.PRINTLN (person); // Person [Name=liuchunfu, id=125]    }

Of course, the above-created object passing parameters, in addition to being able to create the object by passing in the default parameters, can also be passed through the setter method later.

Original connection: Three ways to create objects in spring

Three ways to create objects "Spring"

Related Article

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.