Spring Dependency Injection (first, injection mode)

Source: Internet
Author: User

Spring is a framework that relies on injection (inversion of control), so where does dependency injection (subscript control inversion) appear?

That is, a property (other object) in a class no longer needs to be manually new or created through a factory method, but rather the spring container is injected when the property is used.

There are 2 ways of injecting:

1. attribute Injection : +setter method Injection via parameterless constructor

2. Construction injection : injected by a constructor function with a parameter.

Advantages and Disadvantages

1. Attribute injection is straightforward, the disadvantage is that when it comes to attributes, many constructors appear to be bloated.

2. Construction injection is a high-cohesion embodiment, especially for some attributes that need to be assigned when the object is created, and subsequent modifications are not allowed (no setter method is provided).

Let's look at an example:

1. Create a new interface Ipet

 Package entities;  Public Interface Ipet {    public  String getName ();      Public void setName (String name);      Public void sleep ();}

2. New two classes of dog and cat

 Packageentities; Public classCatImplementsipet{//when the program runs, the properties of the cat are injected in place of the XML file's attributes    PrivateString name = "Kitty"; Private intAge = 2;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; } @Override Public voidsleep () {System.out.println (name+ "Little Cat Sleeps"); }    }
 Packageentities; Public classDogImplementsipet{ PublicString name;  Public intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }    //Constructing method Overloads     PublicDog (String name,intAge ) {         This. Name =name;  This. Age =Age ; }     Public voidsleep () {System.out.println (name+ "Puppy sleeps."); }}

3. Configuring the Beans.xml File

<?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 ">        <!--point to the Cat class, using the value of the ID directly when called -     <BeanID= "Pet1"class= "entities." Cat ">        <!--Attribute Injection -        < Propertyname= "Name"value= "Tom"></ Property>        < Propertyname= "Age"value= "3"></ Property>    </Bean>   <BeanID= "Pet2"class= "entities." Dog ">        <!--Construct method Injection -        <Constructor-argname= "Name"value= "an"></Constructor-arg>        <Constructor-argname= "Age"value= "4"></Constructor-arg>    </Bean>   </Beans>

4. Read the configuration file and run it

 Packageentities;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classTest { Public Static voidMain (string[] args) {//Load configuration fileApplicationContext context =NewClasspathxmlapplicationcontext ("Beans.xml"); //read the ID of cat and Dog in the XML fileIpet Pet1 = (ipet) context.getbean ("Pet1"); Ipet Pet2= (Ipet) context.getbean ("Pet2");        Pet1.sleep ();    Pet2.sleep (); }}

Operation Result:

<!--the properties in the Cat class are replaced by the attributes of the XML file-->tom kitten sleeps.
<!--read the constructor of an XML file, assign a value to the property through the constructor in the dog class-->an the puppy sleeps.

Spring Dependency Injection (first, injection mode)

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.