The Spring learning IOC

Source: Internet
Author: User
Tags ip number

I. IoC (inversion of control, inversion of controls)

We have the experience in developing Java programs that each business logic in a Java program requires at least two or more objects to work together, and usually each object uses a syntax like new object to complete the application of the partner object when using his partner object. You will find that there is a high degree of coupling between objects. The idea of the IOC is that the spring container implements the creation and coordination of these interdependent objects. Objects only need to be relational to the business logic itself. In this respect, the responsibility for how the object gets his co-object is reversed (IOC, DI). Di is actually another way of saying the IOC.

If you don't understand this core concept: Here's an easy-to-understand answer from a blog called Bromon:

The first thing to say is the IOC (inversion of control, controlled inversion). This is the core of spring, throughout. The so-called IOC, for the spring framework, is the responsibility of spring to control the object's life cycle and the relationship between objects. What does that mean, for example, how do we find a girlfriend? The common situation is that we go everywhere to see where there is a beautiful body and good mm, and then inquire about their interests, QQ number, telephone number, IP number, IQ number ..., find ways to know them, give them what they want, then hey ... The process is complex and profound, and we have to design and face each link ourselves. The same is true of traditional program development, in an object, if you want to use another object, you have to get it (your own new one, or a query from Jndi), after the use of the object will be destroyed (such as connection, etc.), the object will always and other interfaces or classes together.
So how does the IOC do it? It's kind of like finding a girlfriend through a dating agency, introducing a third party between me and my girlfriend: the Marriage Institute. Matchmaking management of a lot of men and women's information, I can give a list of matchmaking, tell it I want to find a girlfriend, such as like Michelle Reis, figure like Lin Xire, singing like Jay Chou, speed like Carlos, technology like Zidane, and then the matchmaking will be according to our requirements, provide a mm, We just have to go to love her and get married. As simple as it is, if a matchmaking person doesn't meet our requirements, we'll throw an exception. The whole process is no longer controlled by myself, but by a similar container-like institution that has a matchmaking system. This is how spring advocates for development, and all classes are registered in the spring container, telling spring what you are, what you need, and then spring will give you what you want when the system runs to the right time, as well as handing you over to other things that need you. All classes are created and destroyed by spring, which means that the object that controls the lifetime of the object is no longer a reference to it, but spring. For a specific object, it was previously controlled by other objects, and now all objects are controlled by spring, so this is called control inversion. If you do not understand, I decided to give up.
A key point of the IOC is to dynamically provide the other objects it needs to an object during the system's operation. This is achieved through DI (Dependency injection, Dependency injection). For example, object A needs to manipulate the database, before we always have to write code in a to get a connection object, with spring we just need to tell spring,a need a connection, as for this connection how to construct, when to construct , a does not need to know. When the system is running, Spring creates a connection at the right time, and then, like an injection, it injects into a, which completes the control of the relationship between the various objects. A relies on connection to function properly, and this connection is injected into a by spring, and the name of the dependency injection comes in. So how is di implemented? An important feature after Java 1.3 is reflection (reflection), which allows the program to dynamically generate objects, execute methods of objects, and change the properties of objects when it is run, and spring is injected through reflection. Refer to Java Doc for information on reflection.

Second, the injection based on the XML file configuration

Here first constructs a project, the project directory is probably like this:

This simple project is divided into DAO layer, service layer, model layer, the class name with the letter "I" is the interface, the call relationship between the layers is this:

The steps to inject the XML configuration file are as follows:

1. Import the corresponding jar package from spring
2. Create the corresponding beans.xml in the SRC directory
3. Add the appropriate schema for Beans.xml
<beans xmlns= "Http://"
Xmlns:xsi= "Http://"
Xsi:schemalocation= "Http://
Http:// ">

4. Create a new class
5. Creating an object in Bean.xml
<!--The following configuration is equivalent to complete: HelloWorld HelloWorld = new HelloWorld ()--
<bean id= "HelloWorld" class= "Com.hh.spring.model.HelloWorld" ></bean>
6. Use this object in a test class
6.1 Creating a spring factory
Beanfactory factory = new Classpathxmlapplicationcontext ("Beans.xml");
6.2 Get the appropriate objects from the Spring factory
HelloWorld HelloWorld = Factory.getbean ("HelloWorld", Helloworld.class);

The file in the model layer is simple, with only the ID and username two attributes, the code is as follows:

public class User {private int id;private String username;//omit Setter and getter method}

The Iuserdao interface in the DAO layer defines three methods, namely the Add,delete,load method, Userdao implements the Iuserdao interface:

public class Userdao implements Iuserdao {@Overridepublic void Add (user user) {System.out.println ("add:" +user);} @Overridepublic void Delete (int id) {System.out.println ("delete:" +id);} @Overridepublic User load (int id) {SYSTEM.OUT.PRINTLN ("load:" +id); return null;}}

The service layer's Iuserservice interface defines three methods, three of which call three methods in Iuserdao, so in the userservice implementation, it relies on the Iuserdao class:

public class UserService implements Iuserservice {private Iuserdao userdao;public Iuserdao Getuserdao () {return userdao;} public void Setuserdao (Iuserdao userdao) {This.userdao = Userdao;} @Overridepublic void Add (user user) {userdao.add (user);} @Overridepublic void Delete (int id) {userdao.delete (id);} @Overridepublic User load (int id) {return userdao.load (ID);}}

Finally, the useraction layer, this layer calls the method in UserService to implement the corresponding functions. Note: It is important to write the setter method of the dependent object, based on how the XML configuration file is injected.
public class Useraction {private User user;private iuserservice userservice;private int id;private list<string> nam es;//omitting setter and getter methods}

Finally, the content of the Beans.xml configuration file, we can clearly see from the configuration file the dependencies between classes.

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://" xmlns:           Xsi= "Http://" xsi:schemalocation= "Http:// Http:// "> <!--the following configuration is equivalent to complete: HelloWorld HelloWorld = new HelloWorld ()-<bean id= "HelloWorld" class= "Com.hh.spring.model.HelloWorld" &GT;&LT;/BEAN&G                T        <bean id= "Userdao" class= "Com.hh.spring.dao.UserDao" ></bean> <!--Create a user object and inject the property value--         <bean id= "user" class= "com.hh.spring.model.User" > <property name= "id" value= "2" ></property> <property name= "username" value= "WU Energy" ></property> </bean> <!--autowire= "Bytype" means injection based on type, if there are two objects of the same type in a class will throw an exception, development is generally used byname byname to represent name completion injection. Although automatic injection can reduce configuration, it is not recommended to use the Beans.xml file to understand the structure of the entire class, so AutowIRE--<bean id= "UserService" class= "Com.hh.spring.service.UserService" autowire= "ByName" > <!-- The value in name calls the Setxxx method in the UserService object to inject ref= "Userdao" to indicate that the DAO created in the bean in the configuration file is ID-<!--<prop Erty name= "Userdao" ref= "Userdao" ></property> </bean> <!--for Useraction, The state of the value of the property of the polygon will have different values depending on the thread, so you should use multiple--<bean id= "useraction" class= "com.hh.spring.action.UserAction" scope= "pro ToType "> <property name=" userservice "ref=" UserService "></property> <property name=" User "         ref= "User" ></property> <property name= "id" value= "one" ></property> <!--inject List-- <property name= "Names" > <list> <value>aaa</value> &LT;VALUE&GT;BBB&L t;/value> </list> </property> </bean> <!--The following is the use of constructor injection, not commonly used, which generally makes Injected with the set method, which is the property---        <!--<bean id= "useraction" class= "Com.hh.spring.action.UserAction" scope= "prototype" > <constr Uctor-arg ref= "UserService" ></constructor-arg> </bean>--</beans>

Three, based on the injection of annotation

Annotation-based injection can greatly reduce the content in the XML configuration file, before using the annotation injection method, the XML configuration needs to be as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://"     Xmlns:xsi= "Http://"     xmlns:context= "Http:// /context "     xsi:schemalocation=" Http://         http         Http://         Http:// "><!--open Spring Annotation support   -- <context:annotation-config/>   <!--set which packages spring goes for annotation--and   <context:component-scan Base-package= "Com.hh.spring"/></beans>

The annotations are then added in each class (the annotations are added to the implementation class of the interface, not the interfaces):

Scope represents the creation mode of the bean, with a singleton if the state of the class is not modified, and if there are attributes, attributes, and changes, use multiple examples. Action is typically used in multiple-case mode

The Spring learning IOC

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: 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.