Spring IOC&DI based on XML

1 Inversion of control

  Inversion of Control (Inversion of Control, abbreviated as IoC) is [a design principle in object-oriented programming that can be used to reduce the degree of coupling between computer codes. The most common method is called Dependency Injection (DI), and another method is called Dependency Lookup. Through inversion of control, when an object is created, an external entity that regulates all objects in the system passes the references of the objects it depends on to it. It can also be said that the dependency is injected into the object.

  In Spring, inversion of control is used to reduce the degree of coupling between classes. Spring uses the IoC container to manage relative resources. We hand over the control of all Java bean classes to Spring, which implements the creation of classes. If we need to switch between different implementation classes, such as the persistence layer Dao class or the transaction layer Service class, only a small amount of configuration code is needed to truly reduce the coupling.

2 Commonly used classes

2.1 ApplicationContext和BeanFactory

  • ApplicationContext: It creates objects when building the core container, and the strategy adopted is to use immediate loading. In other words, as soon as the configuration file is read, the objects configured in the configuration file will be created.

  • BeanFactory: It uses lazy loading when building the core container. In other words, when the object needs to be obtained, will the object be actually created.

2.2 ApplicationContext three implementation classes

  • ClassPathXmlApplicationContext: You can load the configuration file under the classpath, and the configuration file must be under the classpath;
  • FileSystemXmlApplicationContext: You can load configuration files in any path on the disk (must have access permissions);
  • AnnotationConfigApplicationContext: used to read annotations to create a container

2.3 Simple case

public static void main(String[] args) {
    
    
    //1.获取配置文件,创建Spring核心容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("Spring.xml");

    //2.根据id获取Bean对象
    IAccountService as  = (IAccountService)ac.getBean("accountService");
    IAccountDao adao = (IAccountDao) ac.getBean("accountDao");

    // 3.查看对象是否创建成功
    System.out.println(as);
    System.out.println(adao);

    // 4.查看依赖注入是否成功
    as.saveAccount();
}

3 ways to configure beans

  There are usually three ways to configure a bean in a Spring configuration file: using the constructor, using the normal method of the factory, and using the static method of the factory .

  The first way: use the constructor to create. When the bean tag is used in the spring configuration file with id and class attributes, and there are no other attributes and tags. The default constructor is used to create the bean object. At this time, if there is no default constructor in the class, the object cannot be created. Or you can use dependency injection to create a bean using a parameterized constructor.

<bean id="accountService" class="service.impl.AccountServiceImpl">
	<!--此时默认使用AccountServiceImpl的无参构造函数进行对象的创建  -->
</bean>

  The second way: Use the ordinary method in the factory to create the object (that is, use the method in a certain class to create the object and store it in the spring container)

<bean id="instanceFactory" class="factory.InstanceFactory">
    <!--配置一个工厂,其中提供一个普通方法getAccountService,该方法返回accountService的实现类  -->
</bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method= "getAccountService">
    <!--使用工厂instanceFactory中的方法getAccountService -->
</bean>

  The third way: use the static method in the factory to create the object (use the static method in a certain class to create the object and store it in the spring container)

<bean id="accountService" class="factory.StaticFactory" factory-method="getAccountService">
    <!--使用工厂StaticFactory中的静态方法getAccountService  -->
</bean>

4 Scope and life cycle of bean

4.1 Scope

The scope of the bean includes five types, which can be specified using the scope attribute of the bean tag:

  • singleton: singleton (default value)
  • prototype: multiple cases
  • request: the scope of the request acting on the web application
  • session: the scope of the session acting on the web application
  • global-session: The session scope (global session scope) that acts on the cluster environment. When it is not a cluster environment, it is the session
<bean id="accountService" class="service.impl.AccountServiceImpl" scope="prototype">

</bean>

4.2 Life cycle

Singleton object:

  • Birth: The object is born when the container is created;
  • Alive: As long as the container is still there, the subject is alive;
  • Death: the container is destroyed, and the object dies;
  • Summary: The life cycle of a singleton object is the same as that of a container.

Multiple objects:

  • Born: When we use objects, the spring framework creates them for us;
  • Alive: The subject is alive as long as it is in use;
  • Death: When an object is not used for a long time and there is no other object reference, it is collected by the Java garbage collector.
<bean id="accountService" class="service.impl.AccountServiceImpl" scope="prototype" init-method="init" destroy-method="destroy">
	<!--可以指定init和destroy方法  -->
</bean>

5 dependency injection

There are two ways to configure dependency injection in the xml file: using the constructor and the set method

5.1 Constructor injection method

Constructor injection (the class must provide the corresponding construction method):

  • Tag: constructor-arg
  • Where the label appears: inside the bean label
  • The attributes in the label (commonly used are name + value or name + ref)
    • type: used to specify the data type of the data to be injected, which is also the type of one or some parameters in the constructor
    • index: Used to assign the data to be injected to the parameter at the specified index position in the constructor. The position of the index starts from 0
    • name: Used to assign the parameter assignment with the specified name in the constructor
    • value: used to provide basic type and String type data
    • ref: used to specify other bean type data, this type must be configured in the IoC container
<bean id="person" class="domain.Person">
    <constructor-arg name="name" value="Tom"></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="birthday" ref="birth"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="birth" class="java.util.Date">
    <!--配置一个日期对象,可以供给person对象注入  -->
</bean>

5.2 Use P tag injection

P tag injection (the class must provide the corresponding set method):
add P tag dependency in the upper part of the xml 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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="student" class="domain.Student" p:name="小明" p:age="23">
</bean>

5.3 set method injection

5.3.1 Common types

set method injection (the class must provide the corresponding set method):

  • Label: property
  • Location: inside the bean tag
  • Attributes:
    • name: used to specify the name of the set method called during injection
    • value: used to provide basic type and String type data
    • ref: used to specify other bean type data, this type must be configured in the IoC container
<bean id="person" class="domain.Person">
    <property name="name" value="Tom" ></property>
    <property name="age" value="21"></property>
    <property name="birthday" ref="birth"></property>
</bean>

<!-- 配置一个日期对象 -->
<bean id="birth" class="java.util.Date">
    <!--配置一个日期对象,可以供给person对象注入  -->
</bean>

5.3.2 Complex types

<bean id="complex" class="domain.Complex">
    <property name="myStrs">
        <!--注入一个数组  -->
        <set>
            <value>AAA</value>
            <value>BBB</value>
            <value>CCC</value>
        </set>
    </property>
    <property name="myList">
        <!--注入一个list   -->
        <array>
            <value>AAA</value>
            <value>BBB</value>
            <value>CCC</value>
        </array>
    </property>
    <property name="mySet">
        <!--注入一个Set   -->
        <list>
            <value>AAA</value>
            <value>BBB</value>
            <value>CCC</value>
        </list>
    </property>
    <property name="myMap">
        <!--注入一个map   -->
        <props>
            <prop key="testC">ccc</prop>
            <prop key="testD">ddd</prop>
        </props>
    </property>
    <property name="myProps">
		<!--注入一个属性集properties   -->
        <map>
            <entry key="testA" value="aaa"></entry>
            <entry key="testB">
                <value>BBB</value>
            </entry>
        </map>
    </property>
</bean>

Guess you like

Origin blog.csdn.net/Orange_minger/article/details/114466018