Spring - concept, DI

Posted by mr00047 on Thu, 24 Oct 2019 13:18:55 +0200

Article directory

Spring


Spring has a lot of functions at present. Common DI and MVC are common in development. It is also common to use spring to manage other frameworks. Spring's biggest role in the project is to decouple, reduce the overall coupling of the project, and try to achieve low coupling. The core of spring is IOC and AOP. IOC control reverses the creation of bean objects, and completes the data encapsulation of bean objects through DI dependency injection.
IOC is a development idea, DI is a development implementation
The official website documents are located below
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-introduction
Can be viewed through chrome translation

1 concepts of dependency injection (DI) and inversion of control (IOC)

Although the industry often mentions IOC and DI, they all mean the same thing, but IOC is the design and development idea proposed by spring, and DI is the code implementation method. The actual meaning is that the calling object does not need to construct the called object itself, but requests the called object from spring. Spring will generate the specified object and inject it into the calling object. This whole process is called dependency injection.
(PS: Spring reflects dependency injection through set method, so you need to add set method for all content to be injected, otherwise injection cannot be implemented.)

In depth understanding of DIP, IoC, DI and IoC containers, please refer to the blog:
https://www.cnblogs.com/liuhaorain/p/3747470.html

2 create maven project steps

  1. Create a normal maven project, and add the core dependency of spring in pom.xml file:
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.3.15.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>4.3.15.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.15.RELEASE</version>
</dependency>
  1. Generate the corresponding java and resources folders, and configure the corresponding format:
  2. Create spring's xml file in resources: (spring.xml)
  3. Create a bean class and a console control class (test class)
public class Student {
    private Teacher teacher;
    private String name;
    private Double height;
    private Integer id;
    private Date birthday;
    private Set set;
    private Properties properties;
    private String[] hobby;
    private List list;
    private Map<String,Object> map;
    public Student() {
        System.out.println("Creating object......");
    }
    public Student(int age) {
        System.out.println("Creating object 2......"+age);
    }
    public Student(String name) {
        System.out.println("Creating object 3......"+name);
    }
    public Student(int age,String name) {
        System.out.println("Creating object 4......"+age+name);
    }
    // getter,setter......
  1. In the spring configuration file, create a bean object (spring.xml)
<!--hold Student Hand  Spring Conduct management-->
    <bean name="student" class="bean.Student"></bean>
    <bean name="Student2" class="bean.Student"></bean>
    <!--Another alias  Student2==student2 -->
    <alias name="Student2" alias="student2"></alias>
    <bean name="st" class="bean.Student">
        <constructor-arg name="name">
            <!--Call the corresponding constructor injection object and set the constructor parameters-->
            <value>Ha ha ha</value>
        </constructor-arg>
    </bean>
  1. Test class
    Dependency injection multiparameter constructor
public class TestApp {
   static  ApplicationContext  context;
    @BeforeClass
    public static void get(){
        //Parsing xml to get the upper and lower text objects of spring (getting IOC container) has created the objects and put them into the container.
        context = new ClassPathXmlApplicationContext("spring.xml");
    }
    @Test
    public void getStudentBean() {
        System.out.println("___________________________________");
        //Get object singleton in IOC container
        //Getting objects with types
//        Student student = context.getBean(Student.class);
        //Get object by configuration name
        Student student2 = (Student)context.getBean("student");
//        System.out.println(student == student2);//true
        Student student3 = (Student)context.getBean("student3");
    }
    @Test
    public void getStudentBeanConstruction() {
        System.out.println("-----------");
        Student st = (Student) context.getBean("st");
        System.out.println(st.getName());
    }
}

3 dependency injection

3.1 dependency injection String, class object

<bean name="setPropertys" class="bean.Student">
	//One property assignment
	<property name="name">
		<value type="java.lang.String">Mei Mei Han</value>
    </property>
    <property name="height">
    	<value type="java.lang.Double">180.2</value>
    </property>
    <property name="id">
    	<value type="java.lang.Integer">1</value>
    </property>
    // Reference - December 12, 1997
    <property name="birthday" ref="birthdayValue"></property>
    <property name="teacher"  ref="teacher"></property>
</bean>
// Date of birth value object
<bean name="birthdayValue" class="java.util.Date">
    <constructor-arg index="0"><value>1997</value></constructor-arg>
    <constructor-arg index="1"><value>12</value></constructor-arg>
    <constructor-arg index="2"><value>12</value></constructor-arg>
</bean>
<bean name="teacher" class="bean.Teacher">
///Property injection with setter method
	<property name="name" value="Kong Hao"></property>
</bean>

This method constrains the incoming type and can only load String type. In development, this method will be chosen more often, because the type is clear at a glance (PS: in Spring, three kinds of dependency injection, set method injection and constructor injection, and of course, the interface injection used in later framework integration)

3.2 dependency injection List,Array,Map,Set

<bean name="setCollection" class="bean.Student">
	 <property name="list">
		<list>
        	<value>Mei Mei Han</value>
            <value>12.5</value>
            <ref bean="teacher"></ref>
        </list>
	</property>
    <property name="hobby">
        <array>
            <value>Kong Hao melon skin</value>
            <value>Tao Qian Han Han</value>
        </array>
    </property>
    <property name="map">
        <map>
            <entry key="number" value="12"></entry>
            <entry key="varchar" value="Mei Mei Han"></entry>
            <entry key="object"  value-ref="teacher"></entry>
        </map>
    </property>
    <property name="set">
        <set>
            <value>123412</value>
        </set>
    </property>
    <property name="properties">
        <props>
            <prop key="url">jdbc:mysql://localhost:3306/test</prop>
            <prop key="driver">com.mysql.jdbc.Driver</prop>
            <prop key="username">root</prop>
            <prop key="password">123</prop>
        </props>
    </property>
</bean>

PS: the three interface types of List Set Array, Spring is injected through the Collection parent interface, so in xml configuration, < list > < set > < array > can be used in general, but if the type defined in the bean is a direct implementation type, such as list, where ArrayList is defined, Spring can only inject with the list tag, so < set > < arr The same goes for ay >

3.3 dependency injection internal bean object

<bean id="TwoBean" class="cn.beans.TwoBean">
	<property name="oneBean">
		<bean class="cn.beans.OneBean">
			<property name="name" value="zhangsan" />
		</bean>
	</property>
</bean>

3.4 null and null

<bean class="bean.Teacher">
    <property name="name">
        <null/>
    </property>
</bean>

<bean class="cn.thinknovo.spring.bean.TestPerson">
    <property name="username" value=""/>
</bean>

4 Spring XML merge

If all the xml files are in the resources root directory, you can import the rest of the spring xml files through the import tag:

In this way, we only need to read the current xml file to finish reading all configuration content. Of course, we can also create subfolders in the resources folder to separate and make the resource files more organized.

When loading, just add the corresponding directory.

Struts2- < include file = "user.xml"/>
Hibernate- < mapping resource = "user.hbm.xml"/>
Spring- < import resource = "spring.xml"/>

Topics: Spring xml Java Maven