IOC and DI of Spring

It turns out that in development, an object is always instantiated using the keyword new when creating an object. Create objects through active instantiation. As a result, many objects cannot be recycled, and if there are dependencies between classes, there will be a high degree of coupling. The original implementation is given below.


    @Test
    public void demo01(){
        //变为面向接口编程
        UserService userService = new UserServiceImpl();
        userService.addUser();
    }

1.IOC

If you need to modify the implementation class of UserService, then the code content of demo01 should also be modified. The principle of software development is low coupling, so find a way to dynamically give the complete class name by relying on the configuration file, and then use the reflection mechanism to generate the object. This is IOC (Control Inversion), which is to manually create the class and let Spring do it.

<?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">
    <!-- 配置service 
        <bean> 配置需要创建的对象
            id :用于之后从spring容器获得实例时使用的
            class :需要创建实例的全限定类名
    -->
    <bean id="userService" class="com.IOCtest1.UserServiceImpl"></bean>
</beans>
    @Test
    public void demo02(){
        //从spring容器获得
        //1 获得容器
        String xmlPath = "com/IOCtest1/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        //2获得内容 --不需要自己new,都是从spring容器获得
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.addUser();

    }

Write a picture description here

Different business codes and specific implementation classes are associated through the IOC container. Greatly reduce the degree of coupling.

2.Of

If there are inter-class dependencies, objects of one class are used as attributes of another class.
Here BookServiceImpl needs to call a method of BookDao, using set injection.

public class BookServiceImpl implements BookService {

    // 方式1:之前,接口=实现类
//  private BookDao bookDao = new BookDaoImpl();
    // 方式2:接口 + setter
    private BookDao bookDao;
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public void addBook(){
        this.bookDao.save();
    }

    public BookServiceImpl() {
        System.out.println("BookService被创建了");
    }

}

Configuration file

<?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">

    <bean id="bookService" class="com.Ditest1.service.BookServiceImpl">
        // 联系起来
        <property name="bookDao" ref="bookDao"></property>
    </bean>
    <bean id="bookDao" class="com.Ditest1.dao.BookDaoImpl"></bean>
</beans>

<property>Used for property injection
name: the property name
of the bean, the ref is obtained through the setter method : the reference
class of the id value of the dependent bean is to tell the IOC the fully qualified name of this class

Test case

    @Test
    public void test02(){
        String xmlPath="com/Ditest/applicationContext.xml";
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
        BookService bookService=(BookService) applicationContext.getBean("bookService");
        bookService.addBook();
    }

Spring IOC uses a complete idea:

We use the xml configuration file (properties file can also) to declare and manage the bean, each bean represents the object to be created, and through the property and other classes or properties. This way the Spring container can know that we want to create a bean instance.
Then use ClassPathXmlApplicationContext in the Java code to load the configuration file to generate the instance object. Complete the corresponding function code.

//默认查找classpath路径下的文件
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring/spring-ioc.xml")
//默认为项目工作路径 即项目的根目录 
FileSystemXmlApplicationContext applicationContext=
                new FileSystemXmlApplicationContext("/src/main/resources/spring/spring-ioc.xml");

3. Spring Dependency Injection (DI)

1. Constructor injection


Set the constructor with parameters. The spring container will decide which constructor to call based on the constructor parameters specified in the bean.
xml configuration file:

<!-- 通过构造注入依赖 -->
<bean name="accountService" class="com.springIoc.service.impl.UserServiceImpl">
    <!-- 构造方法方式注入userDao对象,-->
    <constructor-arg  ref="userDao"/>
</bean>
<bean name="userDao" class="com.springIoc.dao.impl.UserDaoImpl"/>
public class UserServiceImpl implements UserService{
    /**
     * 需要注入的对象Dao层对象
     */
    private UserDao userDao;

    /**
     * 构造注入
     * @param  
     */
    public UserServiceImpl(UserDao userDao){
        this.userDao=userDao;
    }
    //........
}

2. Set injection


Set the Setter () method of the attribute variable in the class.
The above example uses the set method to inject.

3. Automatic assembly

default-autowire=”no/default/constructor|byType|byname” //全局注释
autowire=”no/default/constructor|byType|byname”

"In the byTpye mode, the Spring container will look at the class defined by the bean based on reflection, and then find the bean with the same dependency type to inject into another bean. This process needs to be completed with the help of setter injection, so there must be a set method, otherwise the injection fails "

Auto-wiring of the same byName pattern, at this time Spring will only try to match the property name with the bean name, and if it is found, inject the dependent bean.

For the constructor mode, in this mode, the Spring container will also try to find those beans whose type matches the constructor and then inject.

Published 137 original articles · Like 123 · Visit 250,000+

Guess you like

Origin blog.csdn.net/lz20120808/article/details/79056685
Recommended