We all know that in a software system with object-oriented approach design, its underlying implementation is composed of multiple objects, all the objects through the cooperation between each other, ultimately realize the business logic of the system, in order to solve the problem of coupling between objects, Spring's IOC theory, Used to achieve "decoupling" between objects. IOC's Chinese meaning is "inversion of control", the popular understanding of the right to reverse, the original object is created by the programmer to write the new code, new out of a class object, in the method of invoking it, when the code project together, it exposes a problem: the more the class of new, the more difficult to manage. So spring's IOC is to put the object of creation in the spring container, is to throw things to the container to do, and no longer a programmer a new.
Spring's dependency injection can be assembled manually or automatically.
Let's start with the manual assembly methods that are used frequently.
There are three types of manual assembly methods:(1) Set method Injection (2) Construction method Injection (3) factory method injection (Spring does not support interface injection)
1.Set Injection Mode, properties
by using the parameterless constructor set method injection, this method must provide a set approach, otherwise it will report an exception
① first defines an EMP class, and writes a Get set method on one;
Public emp{private Integer ID; Public emp () {}set method; get method;}
② defines an interface Empservice and Empdao interface Empservice is the service class of the EMP, and Empdao is the database operation class of the EPM;
Public Interface Empservice { void save (Object o); void Delete (Integer ID);}} Public Interface Empdao { void del (Integer id); void add ();}
implementation classes for ③empservice and Empdao
Public classEmpserviceimplImplementsEmpservice {PrivateEmpdao DAO; PublicEmpserviceimpl () {} Public voidSave (Object o) {System.out.println ("Save the Staff"); } Public voidDelete (Integer id) {Dao.del (ID); System.out.println ("Removed employees" +ID); } Publicempserviceimpl (Empdao dao) {Super(); This. DAO =DAO; } PublicEmpdao Getdao () {returnDAO; } Public voidSetdao (Empdao dao) { This. DAO =DAO; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub }
Public class Implements Empdao { public Empdaoservice () { } @Override public void del (Integer id) { System.out.println ("employee removed"); }
④xml file Configuration
<?xml version= "1.0" encoding= "UTF-8"? ><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 ">classclass=" Com.an.service.EmpDaoService "></bean></ Beans>
The ID in <bean> is used for marking, which is the symbol of which class;
Class refers to the full name of the classes that need to be created , and the name in the <property> tag is the empdaoservice class the name of the Dao attribute in the empdaoservice class must go to provide a The Set method lets spring pass the value in, because the content of name is not based on the variable name (attribute) and is generated from the Set method ;ref refers to another bean, and here is the pointer to below <bean id="Empdaoserviceid" ... />
⑤ writing test results for testing class
Public classEmpservicetest { Publicempservicetest () {//TODO auto-generated Constructor stub } Public Static voidMain (string[] args) {//Create a spirng factoryApplicationContext ac=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); //Get EmpserviceEmpservice serv= (Empservice) Ac.getbean ("Empserviceimplid"); //Serv.delete (1); }
Operation Result:
Removed employees
Employee 1 Removed
The disadvantage of set injection is that it is not possible to clearly express which properties are required and which are optional , and the advantage of construct injection is that it is impossible to instantiate incomplete or unusable beans by constructing a forced dependency relationship .
2. Construction method Injection with parameters
The injection of this method refers to the constructor injection with parameters, the following example creates two member variable IDs and name, but does not set the object's set method, so the first injection method cannot be supported. The injection method here is injected into the EMP 's constructor, which means that the Id,namer two parameter values are passed in when an EMP object is created .
The ①emp class is written as follows:
Public classEMP {PrivateString name; Private intID; Publicemp () {//TODO auto-generated Constructor stub } PublicEMP (String name,intID) {Super(); This. Name =name; This. ID =ID; System.out.println ("The constructor method was called" +name+ID); } }
The ②xml configuration file is modified as follows:
class= "Com.an.service.emp" id= "emp" > <constructor-arg name= "id" value= "1101" ></ constructor-arg> <constructor-arg name= "name" value= "Anre" ></constructor-arg></bean>
③ Test class
Public class testemp { public testemp () { } publicstaticvoid Main (string[] args) { applicationcontext ac=new classpathxmlapplicationcontext (" Applicationcontext.xml "); EMP e=ac.getbean ("EMP", EMP.class);} }
④ Running results:
A constructor method was called Anre1101
several other ways to inject through the construction method construction injection is especially for some properties that need to be assigned when the object is created, and subsequent modifications are not allowed (setter method not provided )
(1)Direct Assignment According to thedata type (3)according to the index (2)
(1) according to index injection according to the index assignment, the index is starting with 0 :
<constructor-arg index= "0" value= "1101"/><constructor-arg index= "1" value= "Anso"/>
(2) Injection based on data type
This approach is largely not applicable, in there can be several variables of the same basic type in a class, it is easy to confuse the value to which parameter.
<constructor-arg index= "Java.lang.Integer" value= "1101"/><constructor-arg type= "Java.lang.String" value= " Anso "/>
(3) Direct Assignment injection
It is generally not recommended to use assign a value directly to the parameter, which is based on of the parameter Order Platoon , the passed parameter position is incorrect , it will appear problem
<constructor-arg value= "1101"/><constructor-arg value= "Anso"/>
through The object created by Spring is singleton by default, and if you need to create a multi-instance object, you can Add a property after the <bean> tag:
class= "..." scope= "prototype" >
in The <bean> tab, add the Scope property to control the number of objects in the container .
(1) scope = Singlton ( singleton mode), the object is globally unique in the container, and the object is created when the IOC container is initialized
(2) Scope = prototype (multiple cases), the IOC container creates the entity of the object each time the Getbean is called, and each creation is a different object .
Introduction to the Spring Basics IOC Injection