IoC and DI for Spring applications -- Implementation Based on XML

Posted by yendor on Sun, 02 Jan 2022 18:31:13 +0100

What is IoC and DI

IoC (inversion of control): in the abstract, it is an idea that all objects in our development process can be managed by Spring. We can obtain them directly without creating them ourselves, that is, the inversion of object management rights. Specifically, IoC is a container in Spring, a container for managing objects.
DI (dependency injection): in the process of creating an object, Spring assigns values to the attributes that the object depends on. This step is dependency injection.

Implementation based on XML configuration file

1. Basic use

1.1 add dependency

Create Maven project and add Spring core dependencies

    <dependencies>
        <!-- Spring Core dependency -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.17.RELEASE</version>
        </dependency>

        <!-- add to junit Convenient test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

1.2 add Spring configuration file

Add spring - config. In the resources directory XML 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">

</beans>

1.3 register Bean

Register the objects that need to be managed by Spring through the bean tag

<?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">
    
    <!-- adopt bean Label registration -->
    <bean id="userBean" class="com.wxw.pojo.UserBean" />

</beans>

1.4 get Bean

Get the registered Bean from the Spring container in the test class

    @Test
    public void test01(){
        // Load IoC container
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        // Get Bean object from container
        UserBean userBean = applicationContext.getBean(UserBean.class);
        System.out.println(userBean);
    }

2. Method of obtaining Bean

2.1 by ID

Only one ID can be declared

<?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 class="com.gupaoedu.pojo.UserBean" id="userBean"/>
</beans>

2.2 according to name

Name can declare multiple names. Name = "u1,u2,u3" indicates that it will be split into three name attributes [split according to ','; 'space]

<?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 class="com.gupaoedu.pojo.UserBean" id="user1,user2,user3" name="u1,u2,u3"/>
</beans>

2.3 by type

When obtaining by type, if there are multiple objects of this type in the container, an error will be reported. There are two solutions:

  1. Obtained by combining conditions
@Test
public void fun6(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	// UserBean bean = ac.getBean(UserBean.class);
	UserBean bean = ac.getBean("u1",UserBean.class);
	bean.say();
}
  1. By setting the primary attribute, the object whose primary attribute is true is obtained first.

3. Injection mode (DI)

3.1 structural injection

Through construction method injection, you must first provide the corresponding construction method. You can specify the parameters to be assigned through name or index.

<?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 class="com.gupaoedu.pojo.UserBean" id="user">
			<!-- Structural injection -->
			<!-- name
			<constructor-arg name="id" value="666"/>
			<constructor-arg name="userName" value="bobo"/>
			-->
			<!-- index -->
			<constructor-arg index="0" value="999" />
			<constructor-arg index="1" value="gp" />
		</bean>
</beans>

3.2 setpoint injection

The property of setting injection must provide the corresponding setter method

<bean class="com.gupaoedu.pojo.UserBean" id="user1">
	<!-- Set point injection -->
	<property name="id" value="1"/>
	<property name="userName" value="Zhang San"/>
</bean>

3.2.1 different types of set point injection

	// object
	private Cat cat;
	// array
	private String[] favorites;
	// List collection
	private List<Cat> cats;
	// Map collection
	private Map<String,Object> map;
	// configuration file
	private Properties props;
<?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">
	<!-- Register a Cat object-->
	<bean class="com.gupaoedu.pojo.Cat" id="cat" p:nick="tearful" p:color="black"/>
	
	<bean class="com.gupaoedu.pojo.UserBean" id="user">
		<!-- Object injection -->
		<property name="cat" ref="cat">
			<!--<bean class="com.gupaoedu.pojo.Cat" />-->
		</property>
		<!-- Array injection -->
		<property name="favorites">
			<array>
				<value>Basketball</value>
				<value>Mountain climbing</value>
				<value>Go shopping</value>
			</array>
		</property>
		<!-- List injection -->
		<property name="cats">
			<list>
				<bean class="com.gupaoedu.pojo.Cat" p:nick="Floret 1" p:color="gules"/>
				<bean class="com.gupaoedu.pojo.Cat" p:nick="Floret 2" p:color="green"/>
				<bean class="com.gupaoedu.pojo.Cat" p:nick="Floret 3" p:color="yellow"/>
			</list>
		</property>
		<!-- Map injection -->
		<property name="map" >
			<map>
				<entry key="name1" value="Zhang San 1"/>
				<entry key="name2" value="Zhang San 2"/>
				<entry key="name3" value="Zhang San 3"/>
			</map>
		</property>
		<!-- Property file injection -->
		<property name="props">
			<props>
				<prop key="username">root</prop>
				<prop key="password">123</prop>
			</props>
		</property>
	</bean>
</beans>

3.3 simplified structure injection and set point injection

Introduce the corresponding namespace in the Spring configuration file

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<?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"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- Structural injection -->
    <bean class="com.gupaoedu.pojo.UserBean" id="user" c:_0="111" c:_1="lisi">
        <!--
        <constructor-arg index="0" value="999" />
        <constructor-arg index="1" value="gp" />
        -->
    </bean>
    
    <!-- Set point injection -->
	<bean class="com.gupaoedu.pojo.UserBean" id="user1" p:id="222" p:userName="wangwu">
		<!--
	    <property name="id" value="1"/>
	    <property name="userName" value="Zhang San"/>
	    -->
	</bean>
</beans>

3.4 factory injection

3.4.1 static factory injection

package com.gupaoedu.factory;

import com.gupaoedu.pojo.UserBean;

import java.util.HashMap;
import java.util.Map;

public class StaticFactoryDemo {

    public static Map<String,UserBean> hashMap ;

    static {
        hashMap = new HashMap<String, UserBean>();
        hashMap.put("a1",new UserBean());
        hashMap.put("a2",new UserBean());
        hashMap.put("a3",new UserBean());
    }

    /**
     * Method provided by static factory
     * @return
     */
    public static UserBean getInstance(){
        return hashMap.get("a1");
    }
}
<?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">
    <!--  Injection through static factory -->
    <bean class="com.gupaoedu.factory.StaticFactoryDemo" factory-method="getInstance" id="user"></bean>
</beans>

3.4.1 dynamic plant injection

package com.gupaoedu.factory;

import com.gupaoedu.pojo.UserBean;

/**
 * Let everyone's career leave no regrets
 *
 * @author Mr. Bobo [Gupao college]
 */
public class DynamicFactoryDemo {


    public UserBean getInstance(){
        return new UserBean();
    }
}
<?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">

    <!--  Injection through dynamic factory -->
    <bean class="com.gupaoedu.factory.DynamicFactoryDemo" id="dynamicFactoryDemo" ></bean>

    <!--  Get the required object from the factory object-->
    <bean id="user2" factory-bean="dynamicFactoryDemo" factory-method="getInstance"/>

</beans>

Topics: Java Spring