What is dependency injection?

Source: Internet
Author: User
Tags chop
Spring can effectively organize objects at various layers of J2EE applications. Regardless YesAction objects at the control layer, service objects at the business layer, and Dao objects at the persistent layer can be organically coordinated and executed under spring management. Spring organizes objects at different layers in a loosely coupled manner. Action objects do not need to care about the detailed implementation of service objects, and service objects do not need to care about the detailed 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, Dependency Injection. Dependency InjectionThe bean and bean are organized together by the configuration file instead of the hardcoded one. Understanding Dependency Injection

DependencyInjectionDependency injection and inversion of control)YesThe same concept. DescriptionYes: When a role (possiblyYesA Java instance, caller) needs to have a role (there is also a Java instance, called) to assist, in the traditional program design process, generally, the caller 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.

Regardless Yes Dependency InjectionAnd control reversal all indicate that spring lightning uses dynamic and flexible methods to manage various objects. The detailed implementation between objects is transparent to each other. Understanding Dependency InjectionBefore that, let's look at how to solve the following problem 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 must be able to sharpen an ax by himself ). The corresponding situation is that 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 owner (caller) needs to find the factory and buy the ax, so there is no need to care about the production process of the ax. The simple factory design mode of the corresponding Java program.

(3) To enter the "Distribution on demand" society, people who need an ax do not need to find a factory and sit at home to issue a simple command: An ax is required. The ax naturally appeared in front of him. Corresponding spring Dependency Injection.

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

In other cases, the caller does not need to care about the detailed 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 and the called user. 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 is executed 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-called Dependency Injection, YesIn the process of program execution, it is assumed that there is still an object to be called for assistance, you do not need to create the called in the code, DependencyExternal Injection. Spring Dependency InjectionThere is no requirement for the difference between the caller and the called. pojo is fully supported. DependencyLink Management. Dependency InjectionThere are usually two types:

· Set Value Injection.

· Construction Injection. Set ValueInjection

Set Value Injection YesIt refers to the instance to be invoked through the setter method. Such InjectionThe method is simple and intuitive. Dependency Injection. 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 detailed 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 organization uses the spring configuration file to organize the person instance and the axe instance. The configuration file is shown 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>
<! -- All the above three lines apply to all spring configuration filesYesThe same -->
<! -- 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>
<! -- The property element is used to specify the containerInjectionThe axe attribute must be a container.InjectionHereYesSet ValueInjectionTherefore, the Chinese class must have the setaxe Method -->
<Property name = "Axe">
<! -- There will be a bean reference hereInjectionTo Chinese Bean -->
<Ref local = "" stoneaxe "/">
</Property>
</Bean>
<! -- Define stoneaxe Bean -->
<Bean class = Lee. stoneaxe id = stoneaxe/>
</Beans>

From the configuration file, we can see the flexibility of spring management bean. 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 only YesInterface, but must YesReal implementation class.

Spring automatically takes over the property element definition in each bean definition. After Spring runs the constructor without the number of workers 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 spring Injection.

Id attribute of each Bean YesThe unique identifier of the bean. The program uses the ID attribute to query the bean, bean and bean DependencyThe link is also completed through the ID attribute.

The main program section is as follows:
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 run 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, the program does not include a specific person instance and an axe instance in any way. In other words, there is no axe instance for the person instance in the program, and the axe instance is dynamic during execution by spring. Injection.

A person instance does not need to know the detailed implementation of an axe instance, or even the process of creating an axe instance. When the program runs to require an axe instance, spring creates an axe instance and InjectionTo the caller of the axe instance. When the person instance is executed 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 executing 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 execute 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 must 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 files to be compiled -->
<SRC Path = "."/>
<! -- Specify the location of the class library required to compile these java files -->
<Classpath refID = "classpath"/>
</Javac>
</Target>
<! -- Execute a specific main program -->
<Target description = "run the main class" name = "run" depends = "compile">
<! -- Specify the main program to be executed: Lee. beantest. -->
<Java failonerror = "true" fork = "yes" classname = "Lee. beantest">
<! -- Specify the location of the class library required to execute these java files -->
<Classpath refID = "classpath"/>
</Java>
</Target>
</Project>

Suppose we need to rewrite the implementation class of axe. Alternatively, an implementation class is provided for the person instance. The person interface and Chinese class do not need to be changed. You only need to provide an axe implementation, and then make simple changes to the configuration file.

Axe also has the following implementation:
// There is also an implementation class steelaxe of axe.
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 defines an axe implementation: steelaxe. Then, modify the configuration of the Chinese bean and change the original stoneaxe to steelaxe. That is
<Ref local = "" stoneaxe "/">

Change
<Ref local = "" steelaxe "/">

Run the program again. The following result is displayed:

Cutting firewood with a steel axe is really fast

There is no code coupling relationship between person and Axe. DependencyLinks are managed by spring. Setter uses the setter method as the target Bean InjectionAttribute method, called Set Value Injection.

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

So-called Structure InjectionIs completed by the constructor. DependencyInstead of using the setter method. Make a simple change 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 detailed implementation class
Private axe;
// Default constructor
Public Chinese ()
{}
// ConstructInjectionRequired constructor with number of workers
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 InjectionYou also need to make simple changes to the configuration file. 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>
<! -- All the above three lines apply to all spring configuration filesYesThe same -->
<! -- 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>

Running Effect and setting value using steelaxe InjectionThe running effect is 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

What is 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.