Easy understanding of control inversion and dependency injection in Spring, spring reversal

Source: Internet
Author: User

Easy understanding of control inversion and dependency injection in Spring, spring reversal

Let's review the history of computer development. From the first computer with an area of 170 m² square meters and a weight of 30 tons to the current personal notebook, things are more lightweight and feature-rich, this is a trend in the development of things, as well as in the technical field. Enterprise-level JavaBean (EJB) was very successful at the beginning of its creation, however, after a long time, people began to pursue more convenient and lightweight technical framework implementation, so Spring came into being, in addition, Sring has been constantly involved in other fields (here we will not discuss more), and the essence of Spring includes control inversion and dependency injection.

Reverse Control ( Inversion of Control, IOC)

First, let's take a look at the control word, that is, the control"ZhengIn the case of conversion, in any system with a request, at least two classes need to work with each other. In one entry class, use the new keyword to create an object instance of another class, this is like the idea of object-oriented programming,"I" act as an entry class. In this entry class, I buy a pair of disposable chopsticks every time I eat (every time I use them, I need a new pair)In this relationship, it is "I" (called by the caller) every time"Active"To buy disposable chopsticks (another type), I told chopsticks that you honestly came to my hand and I controlled chopsticks. Well, in this context, in real life, it must be unrealistic, and a person is lazy. He will always create an idea that is more convenient for his own life. More specifically, buy a pair of ordinary chopsticks (not a disposable chopsticks) and place them in a container (called the IOC container in Spring). When you need to use them, you can say to the container:Ioc I want to use chopsticks (send a request to the container)Then the chopsticks will be injected into the hand, and in this process,You are no longer the ControllerInstead, it evolved into a requester (although still called by the caller), relying on the container to give you resources, and the control is placed on the container, which is commonly knownControl reversal.

Dependent injection ( Dependency Injection)

In the same example above, how chopsticks come to my hand (that is, how we get the requested class) under the unified control inversion is a dependency injection process.

 

IOC and DI

Hollywood principles in design principles are described as follows,"Don't look for us, let's look for you ",The description on Baidu encyclopedia is"Don't call us, we will call you (don't call us, we'll call you)" is a famous Hollywood principle. In Hollywood, after you submit your resume to the performing arts company, you have to go home and wait. The Performing Arts Company has full control over the entire entertainment project. actors can only passively accept the company's poor performance and complete their own performances as needed.This is a perfect example of IOC. IOC focuses on the design concept, from a conventional method of object creation, that is, a new object, send a "resume" to the IOC container and passively wait for the IOC container to return the resource to you. The reversal of control refers to "actors controlled by the Performing Arts Company". When it comes to dependency, it refers to "actors need a mix of companies". The objects we need must rely on containers to obtain them, this process is dependency injection.In essence, IOC and DI are represented by different dimensions under the same idea..

Code Implementation

Since the process of obtaining resources in the control reversal is called dependency injection, the code implementation here is also focused on dependency injection. There are three methods for dependency injection: constructor injection, set injection, and interface injection.

1.Interface Injection: Define the information to be injected in the interface and complete the injection through the interface. (Spring does not support this injection method. The reason is that Spring claims that it is a non-invasive method. If you use interface injection, is against this principle.

2.Setter Injection

  Let's break away from Spring to implement setter injection.

public interface UserDao{  addUser(String username);      }
Public class UserDaoImpl implements UserDao {@ Override public void addUser (String username) {System. out. println ("Add User:" + username );}}

 

Public class UserMessage {private UserDao userDao; // assign public void setUserDao (UserDaoImpl userDao) {this. userDao = userDao;} @ Override public void addUser (String userName, String password) {userDao. addUser (userName, password );}}

We will observe carefully that the practices here are essentially the same as those of UserDao userDao = new UserDaoImpl (). Here we have to mention polymorphism, that is, the parent class can reference subclass methods, one effect formed here is to reduce the coupling between User Message and UserDao. Think about it again. The reader may say no. the inversion of control and dependency injection you mentioned need to request resources from the container. This container has not been extracted from it, next we will explain how injection is implemented in Spring.

  

<! -- Use spring to manage object creation and object dependencies --> <bean id = "userManager" class = "scau. zzf. service. UserMessage"> <! -- (1) UserMessageImpl uses userDao. Ioc automatically creates the corresponding UserDao implementation, which is managed by the container --> <! -- (2) provide constructors in UserMessageImpl to allow spring to inject UserDao implementation (DI) --> <! -- (3) Let spring manage the creation and dependency of our objects, you must configure the dependency to the core configuration file of spring --> <property name = "userDao" ref = "UserDao"> </property> <! -- Construct an injection --> <! -- <Constructor-arg ref = "userDao"/> --> </bean> <bean id = "UserDao" class = "scau. zzf. dao. userDao "> </bean>

 

First, we need to assemble the Bean, that is, configure the Bean in the Spring container, and then return the Bean object instance. We can read our xml file through XmlBeanFactory to obtain related Bean information.

Public class test {public static void main (String [] args) throws Exception {BeanFactory factory = new XmlBeanFactory (new FileSystemResource ("src/appllication. xml "); UserMessage userMessage = (UserMessage) factory. getBean ("UserMessage"); userMessage. add ("demassia ");}}

In practical applications, we will not manually read the information in Xml or load the configuration file. The bottom layer of Spring has helped me to do this, that is, in practical applications, we only need to send a request. Of course, it is necessary to understand such a process.

Next we will briefly explain how to implement injection through annotations.

@Configurationpublic class UserConfig {    @Bean    public UserDao getUserDao(){        return new UserDao();    }    @Bean    public UserMessage getUserMessage(){        return new UserMesssgae(getUserDao);    }}
@ Configuration is used to make the entire class A Configuration class. @ Bean annotation tells Spring that the method under this annotation will return an object, this object registers the Bean of the dimension Spring application context. By default, Spring Bean is a Singleton, that is, no matter how many times we use getUserDao (), the returned objects are the same from the beginning to the end. For more information about the configuration of JavaConfig, you can refer to the author's article "more elegant configuration of SSH.

  

 

 

 

  

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.