What is dependency injection?

Source: Internet
Author: User
Tags chop
Spring can effectively organize objects at various layers of J2EE applications. No matter YesThe action object of the control layer, service object of the business layer, and Dao object of the persistent layer can be organically coordinated and run under spring management. Spring organizes objects at different layers in a loosely coupled manner. Action objects do not need to care about the specific implementation of service objects, and service objects do not need to care about the specific implementation of persistence layer objects, object calls at each layer are completely interface-oriented. When the system needs to be restructured, the amount of code rewriting will be greatly reduced.

Everything mentioned above must be adapted to the core mechanism of spring,DependencyInjection.DependencyInjectionThe bean and bean are organized together by the configuration file instead of the hardcoded one. UnderstandingDependencyInjection

DependencyInjectionDependency injection and inversion of control)YesThe same concept. DescriptionYes: When a role (possiblyYesWhen one Java instance, caller) needs the assistance of another role (another Java instance, called), in the traditional program design process, the caller usually creates the called instance. However, in spring, the creation of the called instance is no longer completed by the caller, so it is called control inversion. The creation of the called instance is usually completed by the spring container, and thenInjectionCaller, also knownDependencyInjection.

No matterYesDependencyInjectionAnd control reversal all indicate that spring uses dynamic and flexible methods to manage various objects. The specific implementation between objects is transparent to each other. UnderstandingDependencyInjectionBefore that, let's look at how this problem can be solved in various social forms: a person (Java instance, caller) needs an ax (Java instance, called ).

(1) there is almost no social division of labor in the primitive society. The caller can only sharpen an ax by himself ). The corresponding scenario is: the caller in the Java program creates the caller himself.

(2) entering the industrial society, factories appear. The ax is no longer done by ordinary people, but is produced in the factory. At this time, the ax user (caller) needs to find the factory and buy the ax, so there is no need to care about the production process of the ax. Corresponds to the design pattern of the simple factory of Java program.

(3) In the "pay-as-you-go" society, people who need an ax do not need to find a factory and sit at home to issue a simple command: they need an ax. The ax naturally appeared in front of him. Corresponding to springDependencyInjection.

In the first case, when a Java instance caller creates a called Java instance, The called Java class must appear in the caller's code. It is impossible to achieve loose coupling between the two.

In the second case, the caller does not need to care about the specific implementation process of the caller. Instead, the caller needs to find an instance that complies with a certain standard (interface. At this time, the called code is oriented to interface programming, which can decouple the caller from the called one. This is also the reason why the factory mode is widely used. However, the caller needs to locate the factory by himself, and the caller is coupled with a specific factory.

In the third case, the caller does not need to locate the factory by himself. When the program runs to be called, the system automatically provides the called instance. In fact, both the caller and the called are under spring management.DependencyLinks are provided by spring.

The so-calledDependencyInjection,YesWhen the program is running, if you need to call another object for assistance, you do not need to create the called user in the code,DependencyExternalInjection. SpringDependencyInjectionThere are almost no requirements for callers and callers.DependencyLink Management.DependencyInjectionThere are usually two types:

· Set ValueInjection.

· ConstructionInjection.Set ValueInjection

Set ValueInjectionYesIt refers to the instance to be invoked through the setter method. ThisInjectionThe method is simple and intuitive.DependencyInjection. See the following code,YesPerson Interface

// Define the person Interface
Public interface person
{
// Define an ax method in the person Interface
Public void useaxe ();
}
Then YesAxe Interface
// Define the axe Interface
Public interface axe
{
// There is a method for cutting in the axe Interface
Public void chop ();
}
Person implementation class
// Implement the person interface in Chinese

Public class Chinese implements person
{
// Programming for the axe interface, rather than the specific implementation class
Private axe;
// Default constructor
Public Chinese ()
{}
// Set the valueInjectionRequired setter Method
Public void setaxe (axe)
{
This. AXE = axe;
}
// Useaxe method for implementing the person Interface
Public void useaxe ()
{
System. Out. println (axe. Chop ());
}
}

Axe's first implementation class
// The first axe implementation class stoneaxe

Public class stoneaxe implements axe
{
// Default constructor
Public stoneaxe ()
{}
// Implement the chop method for the axe Interface
Public String chop ()
{
Return "cutting firewood slowly ";
}
}

The following uses the spring configuration file to organize the person instance and the axe instance together. The configuration file is as follows:
<! -- BelowYesStandard XML file header -->
<? XML version = "1.0" encoding = "gb2312"?>
<! -- The following line defines the DTD of the spring xml configuration file -->
Http://www.springframework.org/dtd/spring-beans.dtd>
<! -- The above three lines apply to all spring configuration filesYesSame -->
<! -- Root element of the spring configuration file -->
<Beans>
<! -Define the ID of the first bean.YesChinese, class specifies the implementation class of the bean instance -->
<Bean class = Lee. Chinese ID = Chinese>
<! -- Property element is used to specify the containerInjectionThe axe attribute requires the containerInjectionHereYesSet ValueInjectionTherefore, the Chinese class must have the setaxe Method -->
<Property name = "Axe">
<! -- Reference another bean hereInjectionTo Chinese Bean -->
<Ref local = "" stoneaxe "/">
</Property>
</Bean>
<! -- Define stoneaxe Bean -->
<Bean class = Lee. stoneaxe id = stoneaxe/>
</Beans>
From the configuration file, you can see the flexibility of spring bean management. Between bean and bean DependencyLinks are organized in the configuration file, rather than written in the code. By specifying the configuration file, spring can precisely InjectionAttribute. Therefore, the Bean class Element in the configuration file cannot be YesInterface, but must YesReal implementation class.

Spring automatically takes over the property element definition in each bean definition. After Spring executes a constructor without parameters and creates a default bean instance, it calls the corresponding setter method as a program.InjectionAttribute Value. The property value defined by the property will not be automatically created and managed by the bean, but will be passively received by the springInjection.

Id attribute of each BeanYesThe unique identifier of the bean. The program accesses the bean through the ID attribute.DependencyThe link is also completed through the ID attribute.

See the main program section below:

Public class beantest
{
// Main method, program entry
Public static void main (string [] ARGs) throws exception
{
// BecauseYesIndependent applications explicitly instantiate the context of spring.
Applicationcontext CTX = new filesystemxmlapplicationcontext ("bean. xml ");
// Obtain the bean instance by using the person bean ID, which is interface-oriented. Therefore
// Force type conversion to interface type
Person P = (person) CTX. getbean ("Chinese ");
// Directly execute the useraxe () method of person.
P. useaxe ();
}
}
The execution result of the program is as follows:

Cutting firewood with stone axes is slow

When the main program calls the useaxe () method of person, the axe instance must be used in the method body of this method, however, there is no place in the program to couple the specific person instance with the axe instance. In other words, no axe instance is input for the person instance in the program.Injection.

The person instance does not need to understand the specific implementation of the axe instance, or even the axe creation process. When the program runs to an axe instance, spring creates an axe instance andInjectionTo the caller who needs the axe instance. When the person instance runs where an axe instance is required, an axe instance is generated for the person instance.

The caller does not need to care about the implementation process of the called user, but can even omit the factory positioning (actually allocated on Demand !). The following is a simple script for compiling and running the application with ant:

<? XML version = "1.0"?>
<! -- Define the basic information for compiling the project -->
<Project name = "Spring" default = "." basedir = ".">
<! -- Define the library files required to compile and run the project -->
<Path id = classpath>
<! -- Store spring. jar and other third-party class libraries in this path -->
<Fileset dir =.../../lib>
<Include name = "*. Jar"/>
</Fileset>
<! -- At the same time, you also need to reference the compiled class file -->
<Pathelement Path = "."/>
</Path>
<! -- Compile all java files -->
<Target description = "compile all source code" name = "compile">
<! -- Specify the storage location of the compiled class file -->
<Javac DEBUG = "true" destdir = ".">
Deprecation = "false" optimize = "false" failonerror = "true">
<! -- Specify the storage location of the source file to be compiled -->
<SRC Path = "."/>
<! -- Specify the location of the class library required for compiling these java files -->
<Classpath refID = "classpath"/>
</Javac>
</Target>
<! -- Run a specific main program -->
<Target description = "run the main class" name = "run" depends = "compile">
<! -- Specify the main program to run: Lee. beantest. -->
<Java failonerror = "true" fork = "yes" classname = "Lee. beantest">
<! -- Specify the location of the class library required to run these java files -->
<Classpath refID = "classpath"/>
</Java>
</Target>
</Project>
If you need to rewrite the axe implementation class. Or, provide another implementation class for the person instance. The person interface and Chinese class do not need to be changed. You only need to provide the implementation of another axe, and then make simple modifications to the configuration file.

Another implementation of axe is as follows:

// Another axe implementation class steelaxe
Public class steelaxe implements axe
{
// Default constructor
Public steelaxe ()
{}
// Implement the chop method for the axe Interface
Public String chop ()
{
Return "cutting firewood with an axe is really fast ";
}
}
Then, modify the original spring configuration file and add the following line in it:
<! -- Define a steelaxe Bean -->
<Bean class = Lee. steelaxe id = steelaxe/>
This row redefined an axe implementation: steelaxe. Modify the configuration of the Chinese bean and change the original stoneaxe to steelaxe. That is
<Ref local = "" stoneaxe "/">
Change
<Ref local = "" steelaxe "/">
Execute the program again and you will get the following results:

Cutting firewood with a steel axe is really fast

There is no code coupling between person and Axe.DependencyLinks are managed by spring. Use the setter method as the target BeanInjectionAttribute method, called Set ValueInjection.

The replacement of business objects is quite simple.DependencyLinks are separated from the code and managed dynamically through the configuration file.StructureInjection

So-called StructureInjection, Which is accomplished by constructors.DependencyInstead of using the setter method. Make a simple modification to the Chinese class of the previous code. The modified code is as follows:

// Implement the person interface in Chinese
Public class Chinese implements person
{
// Programming for the axe interface, rather than the specific implementation class
Private axe;
// Default constructor
Public Chinese ()
{}
// ConstructInjectionRequired parameter-based Constructor
Public chinse (axe)
{
This. AXE = axe;
}
// Useaxe method for implementing the person Interface
Public void useaxe ()
{
System. Out. println (axe. Chop ());
}
}
In this case, the setaxe method in the Chinese class is not required. When constructing a person instance, spring is the person instance. InjectionInstitute Dependency. Structure InjectionThe configuration file also needs to be modified. The modified configuration file is as follows:
<! -- BelowYesStandard XML file header -->
<XML version = "1.0" encoding = "gb2312"?>
<! -- The following line defines the DTD of the spring xml configuration file -->
Http://www.springframework.org/dtd/spring-beans.dtd>
<! -- The above three lines apply to all spring configuration filesYesSame -->
<! -- Root element of the spring configuration file -->
<Beans>
<! -Define the ID of the first bean.YesChinese, class specifies the implementation class of the bean instance -->
<Bean class = Lee. Chinese ID = Chinese>
</Bean>
<! -- Define stoneaxe Bean -->
<Bean class = Lee. steelaxe id = steelaxe/>
</Beans>
Execution result and use steelaxe to set the value InjectionThe execution results are exactly the same. The difference is that the axe attribute in the person instance is created at different times-Set Value Injection YesCreate a default bean instance and call the corresponding constructor. Injection DependencyLink. Construction InjectionThe bean instance has been created. DependencyLink

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.