Spring learning (1) ioc understanding

Anyone who knows about Spring should know that spring has two important ideas throughout, one is IOC (Inversion of Control) and the other is DI (Dependency Injection). For novices, these two concepts are difficult to understand. I will explain with my own thoughts.

First of all, we need to know why the spring framework is used in program development.

Two concepts are introduced here: coupling and intrusiveness. To put it simply: coupling, which is expressed as the relationship between classes in java, strong coupling means strong dependencies between classes; intrusiveness: the intrusion of the framework into the code, for example, if your project uses struts1, when you want to change the framework It is found that there are too many things to change, such as actionForm, etc., so struts1 is very intrusive to the code. 
It is highly coupled and intrusive in traditional java development. In a project, a class generally depends on many other classes to complete its own operations. We often use the object of the new class to call its methods, which causes the dependency between the two classes to be too strong. Change one place. , often involving many classes and a lot of code. The example of intrusiveness in the previous paragraph can be seen. 
Of course, EJB can also solve the problems of coupling and intrusiveness, but ejb is too dependent on the server and belongs to the heavyweight framework. 
It can be said that in this context, spring came into being, a lightweight framework to solve the complexity of traditional enterprise development; using ordinary javaBeans instead of EJB technology. It can manage the dependencies between objects and objects. We do not need to build objects by ourselves, and transfer this part of the work to the container for completion. It is a framework with low coupling, no aggressiveness to code, and no dependence on servers. 
And this container, the IOC.

How to understand the idea of ​​IOC?

A very popular example, I changed it to make it easier to understand: it is like looking for a girlfriend. The common way is that we rely on various relationships to find this girlfriend (equivalent to a new object), one day we broke up, and before. Those relationships that I have lost are also gone. If you want to find a new girlfriend, you have to rely on a new relationship (renew another object). It is conceivable that this process is very troublesome. So there is a new way to find a partner - a matchmaking agency. This is what we call the IOC method. You tell the matchmaking agency the characteristics of the object you ask for, and he will find you a match directly, without any complicated process in between. , you just need to deal with the things you get along with, you don’t need to worry about the new process, you don’t need any dependencies, even if you want to change one day, just submit the object you need to the matchmaking agency, and you will get the new one you want. object. 
In fact, the purpose of using ioc to create objects is to form dependencies between objects in a "passive" way. In the traditional development process, whether it is a new or an ordinary factory, the target object needs to actively create and actively find the dependent objects it needs. The target object will scatter his energy on unnecessary non-business logic. IOC injects the created object into the target object through DI (dependency injection).

How exactly is Spring IOC implemented?

The matchmaking agency mentioned above is the container of the ioc management object, which is actually an xml file. The object is configured in the xml, parsed through the spring factory class, and the object is created by "reflection". 
The key points of the spring IOC container: 
* The managed object must be defined in the spring configuration file 
* The constructor or setter method must be defined to allow spring to inject the object. 
We can understand the implementation of spring IOC through the following example. This example uses spring 3.2 

1. Configure applicationContext.xml

<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-3.2.xsd">
    <bean id="userDao4MySqlImpl" class="com.bjsxt.spring.dao.UserDao4MySqlImpl"/>
    <bean id="userDao4OracleImpl" class="com.bjsxt.spring.dao.UserDao4OracleImpl"/>
    <bean id="userManager" class="com.bjsxt.spring.manager.UserManagerImpl">
        <!-- 构造方法注入 
        <constructor-arg ref="userDao4OracleImpl"/>
         -->
         <!-- setter方法注入 -->
         <property name="userDao" ref="userDao4OracleImpl"/>
    </bean>
</beans>

2. The injected class:

package com.bjsxt.spring.dao;

public interface UserDao {

    public void save(String username, String password);
}
package com.bjsxt.spring.dao;

public class UserDao4MySqlImpl implements UserDao {

    public void save(String username, String password) {
        System.out.println("--------UserDao4MySqlImpl.save()-------");
    }
}
package com.bjsxt.spring.dao;

public class UserDao4OracleImpl implements UserDao {

    public void save(String username, String password) {
        System.out.println("--------UserDao4OracleImpl.save()-------");
    }
}

3. The injected class:

package com.bjsxt.spring.manager;

public interface UserManager {
    public void save(String username, String password);
}
package com.bjsxt.spring.manager;

import com.bjsxt.spring.dao.UserDao;

public class UserManagerImpl implements UserManager {
    /**
     * 两种方式:如果这个类中需要注入对象,先建立对象属性,
     *      在写构造方法或者settet方法。
     * 
     */
    private UserDao userDao;

/*  public UserManagerImpl(UserDao userDao) {
        this.userDao = userDao;
    } */

    public void save(String username, String password) {
        this.userDao.save(username, password);
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

4. Test class:

package com.bjsxt.spring.client;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.spring.manager.UserManager;

public class Client {

    public static void main(String[] args) {
/*  传统的通过new对象建立类之间的关系
 * UserManager userManager = new UserManagerImpl(new UserDao4OracleImpl());
        UserManager userManager = new UserManagerImpl(new UserDao4MySqlImpl());
        userManager.save("张三", "123");*/
/**
 * IOC思想     通过工厂类解析xml文件,以“反射”的方式创建对象:
 */
        BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserManager userManager = (UserManager)factory.getBean("userManager");
        userManager.save("张三", "123");
/**
 * IOC思想   实际的执行过程,这也是为什么需要setter方法或构造方法的原因:        
 */
//      UserManagerImpl userManager = new UserManagerImpl();
//      userManager.setUserDao(new UserDao4MySqlImpl());
//      userManager.save("张三", "123");
    }
}

In this way, the idea of ​​spring ioc is realized. 



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728518&siteId=291194637