Understanding of spring control inversion and dependency Injection

Source: Internet
Author: User

Understanding of spring control inversion and dependency Injection

1. When it comes to dependency injection (control inversion), you must first understand what dependency is.

Spring calls the relationship of collaboration dependency. If component A calls the method of component B, it can be calledComponent A depends on Component B..

2. What is dependency injection.

In the traditional program design process, the caller usually creates the called instance..

In dependency injection mode, the creation of the called instance is no longer completed by the caller. Therefore, it is called control inversion. The creation of the called instance is usually completed by the Spring container, it is then injected to the caller, which is also called dependency injection.

Understand by yourself: In A word, the spring container controls the specific object B called by component. Component A depends on spring container injection.

Iii. Advantages of dependency Injection.

Whether it is dependency injection or control reversal, Spring uses a dynamic and flexible way to manage various objects. The specific implementation between objects is transparent to each other. Before understanding dependency injection, 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. (This method depends on the Interface)
(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 Spring dependency injection.
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 this 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, and the dependency between the two is provided by Spring.

Delayed loading: container in

Dependency injection organizes Spring beans together with the specified files.It is not coupled in hard coding mode..The implementation of the program completion does not require the caller's implementation, nor does it need to actively locate the factory, This is the bestDecoupling Mode.The dependency between instances is managed by the IoC container..


Iv. Dependency injection Spring implementation

1. Set Value Injection

Set-value injection refers to the IoC container injecting the dependent instance using the setting method of the attribute.


Create an object (Bean) first)

[Java]View plaincopy

1.Public classHelloWorld {

2.PrivateString msg;

3.

4.PublicString getMsg (){

5.ReturnMsg;

6 .}

7.Public voidSetMsg (String msg ){

8.This. Msg = msg;

9 .}

10 .}



Configure applicationContext. xml and instantiate bean.

[Java]View plaincopy

1. Class= "Com. spring. demo. HelloWorld">

2.

3.

Finally, test whether the injected bean can be obtained and print the attributes of the object.

[Java]View plaincopy

1.Public static voidMain (String [] args ){

2. // read the configuration file to obtain the BeanFactory

3. ApplicationContext context =NewClassPathXmlApplicationContext ("applicationContext. xml ");

4. BeanFactory factory = context;

5.

6. HelloWorld hello = (HelloWorld) factory. getBean ("hello ");

7.

8. System. out. println (hello. getMsg ());

9 .}



2. Construct Injection

In addition to setting value injection, there is also another injection method. When constructing an instance, this method has initialized the dependency for it. This method uses constructor to set dependencies, which is called constructor injection.


Create an object (Bean) first)

[Java]View plaincopy

1.Public classHelloWorld {

2.PrivateString msg;

3.

4. // a default no-argument constructor is required

5.PublicHelloWorld (){}

6.

7.PublicHelloWorld (String msg ){

8.This. Msg = msg;

9 .}

10.

11.PublicString getMsg (){

12.ReturnMsg;

13 .}

14.Public voidSetMsg (String msg ){

15.This. Msg = msg;

16 .}

17 .}





Then configure the applicationContext. xml file to instantiate the bean.

[Java]View plaincopy

1. Class= "Com. spring. demo. HelloWorld">

2.

3. HelloWorld!

4.

5.




Finally, test whether the injected bean can be obtained and print the attributes of the object.

[Java]View plaincopy

1.Public static voidMain (String [] args ){

2. // read the configuration file to obtain the BeanFactory

3. ApplicationContext context =NewClassPathXmlApplicationContext ("applicationContext. xml ");

4. BeanFactory factory = context;

5.

6. HelloWorld hello = (HelloWorld) factory. getBean ("hello ");

7.

8. System. out. println (hello. getMsg ());

9 .}



5. Process bean Dependencies

1. Create and initialize a BeanFactory instance based on the bean configuration.
2. dependencies of each bean will appear in the form of attributes, constructor parameters, or static factory method parameters. When these beans are actually created, These dependencies will also be provided to the bean.
3. Each attribute or constructor parameter can be either an actual value or a reference to another bean in the container.
4. Each specified attribute or constructor parameter value must be converted to a specific format or type required by the constructor parameter.

Spring will verify the configuration of each bean in the container when the container is created, including verifying that the attributes referenced by those beans point to a valid bean. Before the bean is actually created, the bean attributes are not set. As the bean is actually created, the dependent bean that serves as the bean and the dependent bean will also be created and allocated.

Vi. Comparison of the two injection methods

1. Set Value injection has the following advantages:

(1) program developers are easier to understand and accept than traditional JavaBean statements. It is more intuitive and natural to set the dependency through the Setting method.
(2) For complex dependencies, if a constructor injection is used, the constructor may be too bloated and difficult to read. When creating Bean instances, Spring needs to instantiate all the dependent instances at the same time, resulting in performance degradation. The use of Set-value injection can avoid these problems.
(3) The constructor with multiple parameters is more bulky, especially when some attributes are optional.

2. constructor injection is not as good as setting value injection. In some specific scenarios, constructor injection is better than setting value injection. Constructor injection also has the following advantages:

(1) constructor can determine the dependency injection sequence in the constructor. injection with limited dependencies takes precedence. For example, injection of some other dependencies in a component depends on Datasource. Using constructor injection, you can clearly determine the injection sequence in the code.
(2) constructor injection is more useful for beans with no dependency changes. Because there is no setting method, all dependencies are set in the constructor. Therefore, you do not have to worry about subsequent code damages to dependencies.
(3) Dependency can only be set in the constructor. Only the creator of the component can change the dependency of the component. For the caller of the component, the dependencies inside the component are transparent, which is more in line with the high cohesion principle.

To sum up the two methods, we recommend that you use the injection policy supplemented by set-value injection and constructed injection. For injection of dependencies that do not need to be changed, use construction injection as much as possible. For injection of other dependencies, Use Value Setting Injection.

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.