Understanding in Spring IoC and DI

What is the DI and IoC

IoC (Inversion of Control Inversion of Control): is a one design principles of object-oriented programming, is used to reduce the degree of coupling between the computer code. The basic idea is: by means of a "third party" decoupling between objects have dependencies.

DI (Dependence Injection dependency injection): The instance variables that are passed to the object (Dependency injection means giving an object its instance variables).

  • Inversion of Control is an idea
  • Dependency injection is a design pattern
  • IoC framework dependency injection as a way to achieve the inversion of control

Why do we need

In the absence of IoC, we have to be in Aclass using Bthe class, it is necessary in Aclass newthe Binstance of the class, so Aclass and Bbetween classes appeared coupling.

public class A {
    private B b = new B();
}

After using IoC, we'll give an example of this operation framework to help us do it.

In Spring IoC

Container is at the heart of Spring, Spring container is responsible for creating the application bean and to coordinate the relationship between these objects through DI.

Spring is not only a container, Spring comes to realize multiple containers can be summarized into two different types:

  1. bean plant ( BeanFactory), the simplest container, DI provides basic support.
  2. Application context ( ApplicationContext), inherited BeanFactory, and provides the application framework level of service.

As developers, we need to tell Spring which objects to be used as bean fitted to the container, the dependency between the bean and bean. Spring provides three main assembly mechanisms:

  • Implicit bean discovery mechanism and automatic assembly
  • Display configuration in Java
  • Display configuration in XML

Here we introduce one by one these three mechanisms.

Autowiring bean

Scan components: spring automatically discovers application context created bean

@Component This class will show notes as a component class, and inform the Spring bean to be created for the class.

@Component
public class Dog {

}

@ComponentScan Notes enabled component scans.

@Configuration
@ComponentScan
public class DemoApplication {

}

Automatic assembly: Spring automatically satisfy dependencies between bean

@Autowired Annotations may act on constructors, methods, properties.

@Component
public class Dog {
    // 属性
    @Autowired
    private Cat cat;

    // 构造器
    // 从Spring 4.3开始,具有单个构造函数的类可以省略@Autowired注释
    @Autowired
    public Dog(Cat cat) {
        this.cat = cat;
    }

    // 方法
    @Autowired
    public void setCat(Cat cat) {
        this.cat = cat;
    }
}

In Java bean assembly

Group monovalent configuration: configure a class declaration, and arranged in the configuration class bean

@Configuration Notes indicate that this class is class configuration, we can create a bean in the configuration class.

@bean Annotation tells Spring This method returns an object that you want to register for the Spring context bean.

/**
 * 普通类
 */
public class BaseBean {

    public void p() {
        System.out.println("Hello bean");
    }
}



/**
 * 配置类
 */
@Configuration
public class BeanConfig {

    // 这个方法返回一个对象,Spring会把这个对象注册为bean
    @Bean
    public BaseBean getBaseBean() {
        return new BaseBean();
    }

}

Injection assembly: in the configuration class is dependent component to another component injection

Two ways to inject bean:

  1. We can call direct getmethod to obtain the corresponding components
  2. In the getmethod to be dependent components as a parameter, Spring when calling this method, you will automatically inject.
/**
 * 普通类
 */
public class BaseBean {

    public void p() {
        System.out.println("Hello bean");
    }
}

/**
 * 普通类
 */
public class UserBean {
    private BaseBean baseBean;

    public UserBean(BaseBean baseBean) {
        this.baseBean = baseBean;
    }
}



/**
 * 配置类
 */
@Configuration
public class BeanConfig {

    // 这个方法返回一个对象,Spring会把这个对象注册为bean
    @Bean
    public BaseBean getBaseBean() {
        return new BaseBean();
    }

    /**
     * 以下为两种注入bean的方法
     */
    // 方法一:直接调用get方法
    @Bean
    public UseBean getUseBean() {
        return new UseBean(getBaseBean());
    }

    // 方法二:当做参数传入,Spring将自动为你注入
    @Bean
    public UseBean getUseBean(BaseBean baseBean) {
        return new UseBean(baseBean);
    }

}

We will use the second method under normal circumstances.

By assembling XML bean

Although we no longer how to use XML assembly bean, but just appeared in the Spring time, XML is a description of the configuration of the main ways, we still need to look at the.

In use JavaConfig, we created a configuration class to assemble bean, and in the XML configuration, we need to create an XML file, and you want to <beans>elemental root.

The most simple Spring XML configuration is as follows:

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

</beans>

Component Configuration

Above text BaseBean, for example, in the XML file we declare it as bean.

<bean id="baseBean" class="com.example.demo.BaseBean" />

Component injection

<bean id="useBean" class="com.example.demo.UseBean"
      c:_="baseBean" />

XML syntax I will not detail here, interested students can learn on their own.

to sum up

In this article we briefly introduced in Spring IoC, we describe three ways in assembly Spring bean: the automated configuration, based on Java and XML-based configuration explicit explicit configuration. They are intended to describe the relationship between the Spring application components and assembly techniques.

Generally we will use automated configuration, try to avoid explicitly configured to bring maintenance costs. If you have to use explicit configuration, we prefer Java-based configuration, which is more powerful than the XML-based configuration, type-safe and easy to reconstruct.

Reference material

Inversion of Control (IoC) and dependency injection (DI)

Spring combat

Spring Secret

Original episode in my book Jane https://www.jianshu.com/p/7f7e089f4909

Guess you like

Origin www.cnblogs.com/chaohangz/p/12043783.html