[Translate]12-spring Dependency Injection

Source: Internet
Author: User
Tags tutorialspoint

Each Java application is coordinated by multiple classes to eventually build the system used by the end user. When writing complex Java applications, the classes should be

May remain independent, because it is easier to reuse code, but also conducive to the development of unit testing. Spring's dependency injection function keeps classes separate from each other

and "glue" them together.

Consider the following scenario: You have a text editor component in your application and you now want to add spell checking to your text editor. Then you may write

Out the following code:

 Public class texteditor {   private  spellchecker spellchecker;        Public TextEditor () {      new  spellchecker ();   }}

In the large code above, the Spellchecker class is aggregated in the TextEditor class, where we call spellchecker a dependency of the TextEditor class. And according to

The work of dependency instantiation is done within TextEditor. This seemingly natural code, in fact, there are quite a lot of problems. Direct instantiation Here

Spellchecker class. In practical applications, the spell checker will have different implementations if we want to switch TextEditor's spellchecker implementation

class, you must modify the code.

After using the control reversal framework, the code is written like this:

 Public class texteditor {   private  spellchecker spellchecker;        Public TextEditor (spellchecker spellchecker) {      this. spellchecker = spellchecker;   }} 

In this code, Spellchecker is passed in through the TextEditor constructor. TextEditor do not care about the implementation of spellchecker. Concrete Real

The present class is injected by the spring container at the time of instantiation of the TextEditor.

Since TextEditor's control over dependency Spellchecker has shifted from texteditor to the spring container, control has been reversed. Control rights

The way to make a reversal is through dependency injection (the principle is the reflection of Java).

There are two ways to rely on injection in spring:

    1. Injection through the bean's constructor parameters
    2. Dependency injection is done through the bean setter method. After instantiating the bean, the spring container reflects the setter method that invokes the bean.

Below we will explain the two kinds of dependency injection methods respectively.

Constructor parameters for Dependency Injection

Using constructor parameters for dependency injection, the spring container takes the bean's dependencies through the bean's parameter constructor as it instantiates the bean.

Injected. The following example is used to demonstrate:

1. Create the package Com.tutorialspoint.di and new Texteditor.java and Spellchecker.java within the package, as follows:

Texteditor.java as follows:

 Package Com.tutorialspoint.di;  Public class texteditor {        private  spellchecker spellchecker;      Public TextEditor (spellchecker spellchecker) {        System.out.println ("Inside TextEditor constructor.") );         this. spellchecker = spellchecker;    }      Public void spellcheck () {        spellchecker.checkspelling ();    }}

Spellchecker.java as follows:

 Package Com.tutorialspoint.di;  Public class spellchecker {        public  spellchecker () {        System.out.println ("Inside spellchecker constructor. " );    }      Public void checkspelling () {        System.out.println ("Inside checkspelling.") );    }}

2. Create a new di.xml configuration file in the SRC directory with the following file contents:

<?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-3.0.xsd ">   <BeanID= "TextEditor"class= "Com.tutorialspoint.di.TextEditor">      <Constructor-argref= "Spellchecker"/>   </Bean>   <BeanID= "Spellchecker"class= "Com.tutorialspoint.di.SpellChecker"/></Beans>

3. Create a new Mainapp.java in package com.tutorialspoint.di with the following contents:

 PackageCom.tutorialspoint.di;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Di.xml"); TextEditor te= (TextEditor) context.getbean ("TextEditor");            Te.spellcheck (); }}

4. Run the program and check the results:

The Constructor-arg element also contains some other properties, as follows:

May remain independent, because it is easier to reuse code, but also conducive to the development of unit testing. Spring's dependency injection function keeps classes separate from each other

[Translate]12-spring Dependency Injection

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.