Introduction and use of Spring IOC

An introduction to IOC and Bean

IOC is also known as DI. Use the constructor parameters, fatory parameters, and properties to set the object instance. When creating a bean in this process, the container will inject these dependencies. The bean itself uses the direct construction of the class to control the instantiation or location of its dependencies. Because the way to create a bean is reversed, it is called Inversion of Control (IoC). To put it bluntly, the object was created in the past through new, but now it is not new, and the object is injected directly through the construction of the class.

org.springframework.beansAnd org.springframework.contextis the core of IOC container. The BeanFactory interface provides the ability to configure objects at a high level; ApplicationContext is a sub-interface of BeanFactory. Its additional functions include AOP features, message and resource processing, event propagation and other functions. It can completely replace BeanFactory, just like the father is a poor farmer and the son is Gao Fushuai; specific containers such as WebApplicationContext provide rich web application functions.

In spring, the object is the skeleton of the application, which is managed by the IOC container, which can also be called a bean; bean instantiation, assembly, and its life cycle are managed by the IOC container. Beans and their mutual dependencies are configured in configuration metadata and then managed and used by the IOC container.

Two container overview

org.springframework.context.ApplicationContextIn fact, it represents the IOC container, which is responsible for the instantiation, assembly, and configuration of Bean. How does the IOC container configure and manage beans? It obtains instructions to manage beans by means of configuration metadata. So what is configuration metadata? Configuration metadata is actually XML, java annotations, and java code.

Spring can be used out of the box through a small amount of ApplicationContext configuration. Usually a single application will create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. Although XML is a traditional configuration metadata format, but you can also use a small amount of XML display declarations to support Java annotations or Java code metadata format. In many application scenarios, many IOC containers will be created instead of one.

When your objects and configuration metadata are complete, the ApplicationContext will be initialized and created, and then you can fully execute the system or application, as shown below:

Insert picture description here

Three initial configuration metadata

spring configuration requires a minimum of one or more of the bean, based xml configuration <bean>requires top-level element in <beans>the interior, the corresponding configuration is based on the java @Bean (Method for above) and annotations @Configuration (for class above) annotation. In the <bean>unique identifier id represents the bean, bean class represents the full name of the class, for example:

<?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="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>
复制代码

Four instantiated container

Provide the ApplicationContext with one or more resource paths in the form of strings, and the ApplicationContext will load these external configuration metadata through this resource path.

ApplicationContext context =
    new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
复制代码

In <property>the properties of the attribute name element indicates javaBean, ref points to define other bean.

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

    <!-- services -->

    <bean id="iocService" class="com.youku1327.ioc.service.IocService">
        <property name="iocDao" ref="iocDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>
复制代码

Five assembly xml

In the actual development, the business layer and the logic layer are separated, that is to say, the coupling degree of an xml configuration bean is too high, we need to define multiple mxl decoupling, but how to refer to beans in another xml in one xml What? We can <import/>load beans from other xml through the element. When introducing external xml, it is the relative path of the current xml, as the following example: services.xml is in the same directory as the current xml, and message.xml is in a subdirectory of the current xml directory.

<beans>
    <import resource="services.xml"/>
    <import resource="resources/message.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>
复制代码

Six use container

ApplicationContext is a high-level factory that maintains a registry of different beans and dependencies. Use the T getBean (String name, Class requiredType) method of this interface to get the bean instance.

6.1 pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>

    </dependencies>
复制代码

6.2 dao

/**
 * @Author lsc
 * @Description <p>ioc dao </p>
 * @Date 2019/10/29 20:04
 */
public class IocDao {
}
复制代码

6.3 service


/**
 * @Author lsc
 * @Description <p> </p>
 * @Date 2019/10/29 20:03
 */
public class IocService {

    private IocDao iocDao;

    private String name;


    public IocDao getIocDao() {
        return iocDao;
    }

    public void setIocDao(IocDao iocDao) {
        this.iocDao = iocDao;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
复制代码

6.4 dao.xml

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

    <!-- services -->

    <bean id="iocDao" class="com.youku1327.ioc.dao.IocDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>
复制代码

6.5 services.xml

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

    <import resource="dao.xml"/>

    <!-- services -->

    <bean id="iocService" class="com.youku1327.ioc.service.IocService">
        <property name="iocDao" ref="iocDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>
复制代码

6.6 application

/**
 * @Author lsc
 * @Description <p> 初始ioc</p>
 * @Date 2019/10/29 22:22
 */
public class Application {

    public static void main(String[] args) {
        // 创建和配置 beans
        ApplicationContext context =
                new ClassPathXmlApplicationContext(new String[] {"services.xml", "dao.xml"});
        // 获得配置的实例
        IocService service = context.getBean("iocService", IocService.class);
        // 使用配置的实例
        service.setName("youku1327");
        System.out.println(service.getName());
    }
}
复制代码

6.7 Output

Insert picture description here

Seven reference documents and public account

The source code is at the end of the article corresponding to the public account.

spring reference

Insert picture description here

Guess you like

Origin juejin.im/post/5e970168f265da47d2025aba