spring-Dependency Injection based on constructors

Source: Internet
Author: User

Spring constructor-based dependency injection

When a container invokes a class constructor with a set of parameters, the constructor-based di is completed, where each parameter represents a dependency on another class.

Contents of the Texteditor.java file:

 Package Com.tuorialsponit;  Public class texteditor {    private  spellchecker spellchecker;      Public TextEditor (spellchecker spellchecker) {        this. Spellchecker= spellchecker;    }         publicvoid  spellcheck () {        spellchecker.checkspelling ();    }}

The following is another dependent class file Spellchecker.java content

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

The following is the contents of the Mainapp.java file

 Public class Mainapp {    publicstaticvoid  main (string[] args) {        new Classpathxmlapplicationcontext ("Beans.xml"); //            TextEditor TextEditor = (texteditor) context.getbean ("TextEditor");        Texteditor.spellcheck ();    }}

The following is the content of the configuration file Beans.xml, which has a configuration based on constructor injection:

<BeanID= "TextEditor"class= "Com.tuorialsponit.TextEditor">         <Constructor-argref= "Spellchecker"></Constructor-arg>     </Bean>          <BeanID= "Spellchecker"class= "Com.tuorialsponit.SpellChecker">     </Bean>

Operation Result:

spring-Dependency Injection based on constructors

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.