Three ways to implement spring Dependency injection (DI)

Source: Internet
Author: User

Spring relies on injection (DI) in three ways, respectively:

1. Interface Injection

2. Setter Method Injection

3. Construct Method Injection

<?xml:namespace prefix = o ns = "Urn:schemas-microsoft-com:office:office"/>

Here's how these three dependency injections are implemented in spring.

First we need the following classes:

Interface Logic.java

Interface Implementation Class Logicimpl.java

A processing class Loginaction.java

There is also a test class Testmain.java

Logic.java as follows:

Package com.spring.test.di;

Public Interface Logic {

Public String GetName ();

}

Logicimpl.java as follows:

Package com.spring.test.di;

Public class Logicimpl implements logic{

Public String GetName () {

return "Fengyun";

}

}

Testmain.java

Package com.spring.test.di;

Import Org.springframework.context.ApplicationContext;

Import Org.springframework.context.support.FileSystemXmlApplicationContext;

public class Testmain {

/**

* @param args

*/

public static void Main (string[] args) {

Get ApplicationContext Object

ApplicationContext CTX = new Filesystemxmlapplicationcontext (

"Applicationcontext.xml");

Get Bean

Loginaction loginaction = (loginaction) ctx.getbean ("Loginaction");

Loginaction.execute ();

}

}

Loginaction.java will vary slightly depending on the injection method used

The following method is injected to see the Loginaction.java class

Setter Method Injection:

Package com.spring.test.di;

Public class loginaction {

Private Logic logic;

Public void Execute () {

String name = Logic.getname ();

System.out.print ("My name is" + name);

}

/**

* @return The logic

*/

Public Logic Getlogic () {

return logic;

}

/**

* @param logic

* The logic to set

*/

Public void setlogic (logic logic) {

this. Logic = logic;

}

}

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.