Application of simple analytic Dependency injection (inversion of control) in spring

Source: Internet
Author: User

Ioc--inversion of Control inversion
Di--dependency Injection Dependency Injection

As we all know, dependency injection is a very important design pattern in spring. Maybe a lot of beginners have a resistance to this seemingly advanced thing.
Simply describe what is dependency injection and how spring is using dependency injection.

dependency: An object in a component that references a B component, which is called a dependent on B
dependencies can cause hard coding between components, the general workaround for resolving dependencies is as follows:

1, a component first creates a B component, and the B component method is called
2, a components first through the factory B to obtain the B components, and then call the B component method
3, A, b two components are managed by the container, the container first pass the B component to the A component, a component directly calls the method of B

The first is the traditional approach and does not solve the dependency
The second one creates a coupling with the factory class.
Spring is solved by a third method, called Dependency injection.

Dependency Injection and control inversion are actually the same design pattern, but are described from different angles.
Dependency Injection is the dependency of the component, which means a no longer actively to create a B component, and become a passive recipient of the injection of the container B object;
The control inversion is from the control of the object, refers to the program code directly manipulate the object's call to the container.

Dependency injection consists of two ways,one is to set the value injection, the first is the construction injection。 The following is an example of a specific code implementation in spring to illustrate two kinds of dependency injection methods:

1, the database operation interface:
1 public interface Userdao { 2 3 void Save ( String name,string Pass); 4 }

2, the interface two ways of realization:
The program simply simulates the connection to the database and does not actually connect:
(1)

1 ImportCom.csu.test.dao.UserDao;2 3  Public classUserdaojdbcImplementsuserdao{4 5 @Override6      Public voidSave (string name, String pass) {7 8System.out.println ("Impersonate the user via JDBC:" +name);9     }Ten  One}



(2)

1 ImportCom.csu.test.dao.UserDao;2 3  Public classUserdaohibernateImplementsuserdao{4 5 @Override6      Public voidSave (string name, String pass) {7 8SYSTEM.OUT.PRINTLN ("Simulate storage of users via hibernate:" +name);9     }Ten  One}


3. Service Layer:

1 ImportOrg.springframework.context.ApplicationContext;2 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;3 4 ImportCom.csu.test.dao.UserDao;5 6  Public classUserService {7     8     PrivateUserdao Userdao;9     Ten      One  A     //1, by providing the Sett method for Userdao, the property in the configuration file is configured to solve the problem of a dependency B -      Public voidSetuserdao (Userdao Userdao) { -          This. Userdao =Userdao; the     } -      -     //2, configuration through the construction method -      PublicUserService (Userdao Userdao) { +          This. Userdao =Userdao; -     } +  A  at  -      Public voidAddUser (String name,string pass) { -         //Userdao Userdao = new Userdao (); -         //Userdao Userdao = new Userdaojdbc (); -         //Userdao Userdao = Userdaofactory.getuserdao (); -          in         /** - The spring container can be created in the//spring to ApplicationContext ctx = new Classpathxmlapplicationcontext ("Beans.xml"); + Userdao Userdao = Ctx.getbean ("Userdao", userdao.class); - Userdao.save (name, pass); the         **/ *          $ Userdao.save (name, pass);Panax Notoginseng     } -}



4, configuration file:

<?xml version= "1.0" encoding= "UTF-8"?><!--the root element of the entire spring file is Beans--><beans xmlns= "/http/ Www.springframework.org/schema/beans "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> &L t;! --This line of code is equivalent to one product--<bean id= "Userdaojdbc" class= "Com.csu.test.dao.impl.UserDaoJdbc"/> <bean id= "Userdaoh Ibernate "class=" Com.csu.test.dao.impl.UserHibernate "/> <bean id =" UserService "class=" Com.csu.test.serv Ice. UserService "> <!--property is the control call setter Method--<!--<property name =" Userdao "ref =" Userdao Jdbc "/>--<!--call the parameter constructor--<constructor-arg ref =" Userdaojdbc "/> <!--replacement implementation Mode-<!--<property name = "Userdao" ref = "Userdaohibernate"/> <constructor-arg ref = "U Serdaohibernate "/>-</bean> </beans> 


Here's the key explanation:
In the service layer of the UserService class, is dependent on the database Operation object Userdao, as you can see, UserService class we did not directly new out Userdao object,
How to do it: two ways
(1), set value injection:
The corresponding function is: public void Setuserdao (Userdao Userdao)
In the configuration file, the corresponding bean setting with ID UserService has a property attribute, which means that when we get the UserService bean object, the container automatically calls the
The set function corresponding to name, which is the function above, is still the Bean object, so ref

(2), Construction injection
The corresponding function is: public userservice (Userdao Userdao)
The implication of injecting a similar,<constructor-arg> tag with a set value is to call the constructor, pass the arguments, and instantiate the Userdao automatically.

Of course, the two ways do not repeat the settings, the above has been commented out one, you can test it yourself.


5. Test the main class:

1 ImportOrg.junit.Before;2 Importorg.junit.Test;3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 ImportCom.csu.test.dao.UserDao;7 ImportCom.csu.test.service.UserService;8 9  Public classTestservice {Ten  One userservice u; A      - @Test -      Public voidTestadduser () { theApplicationContext CTX =NewClasspathxmlapplicationcontext ("Beans.xml"); -U = Ctx.getbean ("UserService", UserService.class); -          -U.adduser ("admin", "123"); +     } -}


In this way, we implement the interface-oriented programming , specific implementation of the class configuration in the configuration file, like the above code, we just need to change the configuration file ,
You can change the operation object of the database.

Application of simple analytic Dependency injection (inversion of control) in spring

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.