What is Dependency injection

Source: Internet
Author: User
Tags chop

Spring can effectively organize the objects of each layer of the Java EE application. No matter is aThe action object of the control layer, the service object of the business layer, or the DAO object of the persistence layer, can be coordinated and run organically under Spring's management. Spring organizes the objects of each layer together in a loosely coupled manner, and the action object does not care about the implementation of the service object, and the service object does not care about the implementation of the persistent Layer object, and the invocation of each layer object is completely interface-oriented. When the system needs refactoring, the amount of rewriting of the code is greatly reduced.

Everything above is well suited to spring's core mechanism, Dependent injectedDependent injectedLet the bean and bean be organized together in a configuration file, rather than in a hard-coded way. Understand Dependent injected

Dependency injection (Dependency injection) and control inversion (inversion of controls) are the same concept. The implication is that when a role (possibly a Java instance, the caller) needs the assistance of another role (another Java instance, the callee), the caller's instance is typically created by callers during the traditional program design process. In spring, however, the work of creating the callee is no longer done by the caller, so called control inversion, and the work of creating the callee instance is usually done by the spring container, which is then injected into the caller and, therefore, also called dependency injection .

No matter is a Dependent injected, or control reversal, means that spring uses a dynamic, flexible way to manage various objects. The concrete implementation of objects and objects is transparent to each other. In understanding Dependent injectedBefore, look at the following question how to solve in various forms of society: A person (Java instance, caller) needs an axe (Java instance, callee).

(1) In primitive society, there was hardly any social division of labor. The person who needs the axe (the caller) can only grind an axe (callee) on its own. The corresponding scenario is: The caller in the Java program creates the callee itself.

(2) Enter the industrial society, the factory appears. The axe is no longer done by ordinary people, but is produced in the factory, where the person needing the axe (the caller) finds the factory, buys the axe, and does not care about the manufacturing process of the axe. A simple factory design pattern that corresponds to a Java program.

(3) To enter the "On demand" society, people who need an axe do not need to find a factory, sitting at home to send a simple command: Need an axe. The axe appeared to him naturally. corresponding to the spring Dependent injected

In the first case, the caller of the Java instance creates the invoked Java instance, which inevitably requires the called Java class to appear in the caller's code. The loose coupling between the two cannot be achieved.

In the second case, the caller does not have to care about the specific implementation of the callee, only need to find an instance that conforms to a certain standard (interface) to be used. The code invoked at this point is interface-oriented programming, which allows the caller and callee to be decoupled, which is why the factory pattern is heavily used. But the caller needs to locate the factory itself, and the caller is coupled with the particular factory.

In the third case, the caller does not need to locate the factory himself, and the system automatically provides the callee instance when the program runs to the caller. In fact, both the caller and the callee are under Spring's management, and the DependentThe relationship is provided by spring.

Called Dependent injectedis aWhen you need to invoke another object assistance while the program is running, you do not have to create the callee in your code, but DependentIn the external injected。 Spring's Dependent injectedThere is almost no requirement for the caller and the callee to fully support the Pojo between DependentManagement of the relationship. Dependent injectedThere are usually two types of:

• Set values injected

• Construction injected

Set Value injection

Set Value injected is aRefers to an instance of the callee passed through the setter method. This injectedis simple and intuitive, so the spring Dependent injectedUsed in large quantities. Look at the code below, is aThe person's interface

Defining the Person interface
public interface Person
{
The person interface defines a method for using an axe
public void Useaxe ();
}


And then is ainterface of the axe

Defining the Axe Interface
public interface Axe
{
There's a way to cut in the axe interface.
public void chop ();
}


The implementation class for person

Chinese implementing the Person interface

Public class Chinese implements person
{
Programming for axe interfaces, not specific implementation classes
Private Axe Axe;
The default constructor
Public Chinese ()
{}
Setter method required to set value injection
public void Setaxe (Axe Axe)
{
This.axe = axe;
}
Useaxe method for implementing the person interface
public void Useaxe ()
{
System.out.println (Axe.chop ());
}
}


The first implementation class of a axe

Axe's first implementation class Stoneaxe

public class Stoneaxe implements Axe
{
Default constructor
Public Stoneaxe ()
{}
The chop method of implementing Axe interface
Public String Chop ()
{
Return "stone axe chopping wood is very slow";
}
}


The following is a spring-based configuration file that organizes the person instances and axe instances together. The configuration file looks like this:

Below!-- is the standard XML file header-->
The following line defines the DTD--> for the spring XML configuration file!--
"Http://www.springframework.org/dtd/spring-beans.dtd" >
The three lines above!-- are the same for all spring configuration files-->
The root element of the!--spring configuration file-->

is Chinese, and class specifies the implementation class of the Bean instance-->

The!--property element is used to specify the attributes that need to be injected by the container, and the axe attribute needs to be injected here, so the Chinese class must have a Setaxe method-->


The!--here injects a reference from another bean to the Chinese bean-->



!--Define Stoneaxe Bean-->


From the configuration file, you can see the dexterity of Spring management beans. Between the bean and the bean DependentRelationships are organized in configuration files, not in code. With the configuration file designation, spring can accurately injectedProperty. Therefore, the class element of the bean in the configuration file cannot be simply is ainterface, and must be is aThe real implementation class.

Spring automatically takes over the definition of the property element in each bean definition. Spring will invoke the corresponding setter method after executing the parameterless constructor, after creating the default Bean instance, as the program injectedThe value of the property. attribute values defined by the property will no longer be actively created and managed by the bean, but instead passively receive spring's injected

The ID property of each bean is aThe unique identity of the bean, which accesses the Bean,bean with the bean by its ID property. DependentThe relationship is also done through the id attribute.

See the main program section below:

public class Beantest
{
The main method, the entrance to the program
public static void Main (string[] args) throws Exception
{
Because it is a standalone application, the context of spring is explicitly instantiated.
ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Bean.xml");
The bean instance is obtained through the ID of the person bean, and interface-oriented programming is
Force type conversion to interface type here
Person P = (person) ctx.getbean ("Chinese");
Executes the Useraxe () method of the person directly.
P.useaxe ();
}
}


The results of the execution of the program are as follows:

The stone axe is very slow to chop

When the main program calls the person's Useaxe () method, the method's body needs to use an instance of axe, but there is no place in the program to couple specific person instances with axe instances. Or, the program does not pass in an instance of axe for the person instance, and the axe instance is dynamically run by spring injected

The person instance does not need to know the specific implementation of the axe instance, or even the creation process of the axe. When the program runs to a axe instance, Spring creates the axe instance and injectedTo the caller who needs to axe the instance. When the person instance runs to the place where the axe instance is needed, a axe instance is naturally generated for use by the person instance.

Callers not only need not care about the implementation process of the callee, even the factory location can be omitted (really on demand!). The following also gives a simple script to compile and run the app using ant:

!--define the basic information for compiling the project-->

!--define the library files required to compile and run the project-->

for the Spring.jar and other third-party class libraries-->



!--also need to reference the compiled class file-->

" path>
!--Compile all java files-->

!-- Specifies where the compiled class file is stored-->

Deprecation= "false" Optimize= "false" failonerror= "true" >
!--Specifies the location of the source file that needs to be compiled-->





!--Run a specific main program-->

!--Specify the main program to run: Lee. Beantest. -->

!--Specify the class library location required to run these JAVA files-->



project>


If you need to overwrite the axe implementation class. Alternatively, provide another implementation class to use for the person instance. There is no need to change the person interface or the Chinese class. Just provide another implementation of the axe, and then make a simple modification to the configuration file.

Another implementation of axe is as follows:

Another implementation class of axe Steelaxe
public class Steelaxe implements Axe
{
Default constructor
Public Steelaxe ()
{}
The chop method of implementing Axe interface
Public String Chop ()
{
Return "Steel axe chopping wood really fast";
}
}


Then, modify the original spring configuration file and add the following line in it:

!--Define a Steelaxe bean-->


The row redefined the implementation of a axe: Steelaxe. Then modify the configuration of the Chinese bean to change the original incoming stoneaxe to incoming steelaxe. That is


Change into


Executing the program again at this time will result in the following:

Steel axe chopping wood really fast

There is no code-coupling relationship between person and axe, and the bean-to-bean DependentThe relationship is managed by spring. Using setter method as Target bean injectedproperty, called the set value injected

The replacement of a business object becomes quite simple, and the object-to-object DependentRelationships are separated from code and managed dynamically through configuration files.

Construction Injection

The so-called construction injected, which is done through a constructor function. DependentThe relationship is set, not by the setter method. Make a simple modification to the previous code Chinese class, and the modified code is as follows:

Chinese implementing the Person interface
Public class Chinese implements person
{
Programming for axe interfaces, not specific implementation classes
Private Axe Axe;
The default constructor
Public Chinese ()
{}
Construct the constructor with parameters required for injection
Public Chinse (Axe Axe)
{
This.axe = axe;
}
Useaxe method for implementing the person interface
public void Useaxe ()
{
System.out.println (Axe.chop ());
}
}


There is no need to Chinese the Setaxe method in the class, when constructing the person instance, spring is the person instance injectedThe DependentThe axe instance. Structure injectedConfiguration file is also required to make a simple modification, the modified configuration file is as follows:

Below!-- is the standard XML file header-->
The following line defines the DTD--> for the spring XML configuration file!--
"Http://www.springframework.org/dtd/spring-beans.dtd" >
The three lines above!-- are the same for all spring configuration files-->
The root element of the!--spring configuration file-->

is Chinese, and class specifies the implementation class of the Bean instance-->

!--Define Stoneaxe Bean-->


Performing effects and setting values using Steelaxe injectedPerformance is exactly the same. The difference is that the time to create the axe attribute in the person instance is different--set the value injected is aNow create a default bean instance, and then call the corresponding constructor method injected DependentRelationship. and construction injectedWhen you create a bean instance, you have completed the DependentRelationship of

What is Dependency injection (RPM)

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.