What are IoC and DI

IoC(Inversion of Control) : An object-oriented programming design principle used to reduce coupling between computer code. The basic idea is to decouple dependent objects with the help of a “third party”.

(Dependence Injection means giving an object its instance variables) : Dependency Injection means giving an object its instance variables.

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

Why is it needed

Before IoC, if we wanted to use class B in class A, we would create A new instance of class B in class A so that there would be coupling between class A and class B.

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

With IoC, we leave instantiation to the framework to do for us.

In the Spring IoC

The container is at the heart of Spring, which is responsible for creating beans in your application and coordinating the relationships between these objects through DI.

There is no single Spring container. Spring comes with multiple implementations, which can be categorized into two different types:

  1. Bean plant (BeanFactory), the simplest container that provides basic DI support.
  2. Application Context (ApplicationContext), inheritedBeanFactoryAnd provide application framework level services.

As developers, we need to tell Spring which objects to assemble into the container as beans, and the dependencies between beans. Spring provides three main assembly mechanisms:

  • Implicit bean discovery mechanisms and autowiring
  • Display configuration in Java
  • Display configuration in XML

Let’s take a look at each of these mechanisms.

Auto-assembly bean

Component scanning: Spring automatically discovers beans created in the application context

The @Component annotation indicates that this class will bea Component class and tells Spring to create a bean for this class.

@Component
public class Dog {}Copy the code

The @ComponentScan annotation enables component scanning.

@Configuration
@ComponentScan
public class DemoApplication {}Copy the code

Autowiring: Spring automatically satisfies dependencies between beans

The @autoWired annotation can be applied to constructors, methods, and properties.

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

  	/ / the constructor
    // Starting with Spring 4.3, classes with a single constructor can omit the @autowired annotation
    @Autowired
    public Dog(Cat cat) {
        this.cat = cat;
    }

  	/ / method
    @Autowired
    public void setCat(Cat cat) {
        this.cat = cat; }}Copy the code

Assemble beans in Java

Valence configuration: Declare a configuration class and configure beans in the configuration class

The @Configuration annotation indicates that this class is a Configuration class under which we can create beans.

The @bean annotation tells Spring that this method will return an object to be registered as a bean in the Spring context.

/** * Common class */
public class BaseBean {

    public void p(a) {
        System.out.println("Hello bean"); }}/** * Configuration class */
@Configuration
public class BeanConfig {

  	// This method returns an object that Spring registers as a bean
    @Bean
    public BaseBean getBaseBean(a) {
        return newBaseBean(); }}Copy the code

Component injection: Injecting a dependent component into another component in a configuration class

There are two ways to inject beans:

  1. We can just call itgetMethod to get the corresponding component
  2. ingetMethod that passes in the dependent component as an argument, and Spring will inject it for you automatically when it calls the method.
/** * Common class */
public class BaseBean {

    public void p(a) {
        System.out.println("Hello bean"); }}/** * Common class */
public class UserBean {
    private BaseBean baseBean;

    public UserBean(BaseBean baseBean) {
        this.baseBean = baseBean; }}/** * Configuration class */
@Configuration
public class BeanConfig {

    // This method returns an object that Spring registers as a bean
    @Bean
    public BaseBean getBaseBean(a) {
        return new BaseBean();
    }

    /** * There are two ways to inject beans */
  	// Call the get method directly
    @Bean
    public UseBean getUseBean(a) {
        return new UseBean(getBaseBean());
    }

  	// Method two: When passed in as a parameter, Spring will automatically inject it for you
    @Bean
    public UseBean getUseBean(BaseBean baseBean) {
        return newUseBean(baseBean); }}Copy the code

Usually we use method two.

Assemble beans through XML

Although we don’t use XML assembly beans much anymore, when Spring first came along, XML was the primary way to describe configuration, and it’s worth knowing.

With JavaConfig, we created a configuration class to assemble the beans, and with XML configuration, we need to create an XML file with the

element as the root.

The simplest 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">

    <! Configure your bean here -->

</beans>
Copy the code

Component configuration

Take the BaseBean from above, which we declared as a bean in an XML file.

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

Component injection

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

I won’t go into the syntax of XML here, but you can learn on your own if you are interested.

conclusion

This article took a brief look at IoC in Spring and showed you three ways to assemble beans in Spring: automated configuration, Explicit Java-based configuration, and explicit XML-based configuration. These techniques are used to describe components in Spring applications and the relationships between components.

In general, we use automated configuration to avoid the maintenance costs of explicit configuration. If we had to use explicit configuration, we preferred the Java-based configuration, which is more powerful, type-safe, and easier to refactor than the XML-based configuration.

The resources

Inversion of Control (IoC) and Dependency Injection (DI)

The Spring of actual combat

The Spring revelation

The original text was first published in my Jane book Chaohang.top

Please follow my wechat official account [Chaochao Won’t fly] to get the latest updates.