IOC and DI in Spring ("easiest to understand Spring learning")

Keywords: Java Spring Back-end SSM

🏇 wow Click Click : \textcolor{blue} {wow, Kaka:} Wow, Kaka: stay upper one piece writing chapter in simple single Yes solution Yes S p r i n g with and I O C of reason theory PUSH guide \textcolor{green} {in the last article, I briefly understood the theoretical derivation of Spring and IOC} In the last article, I briefly understood the theoretical derivation of Spring and IOC
🏇 that Do you meet lower come see one lower control system back turn I O C of create build square type with and according to Depend on notes enter \textcolor{pink} {next, let's look at the creation method of control inversion IOC and dependency injection} Next, let's take a look at the creation of inversion of control IOC and dependency injection
🏇 in between I Guys also Yes solution one lower S p r i n g in of match Set \textcolor{green} {let's also learn about the configuration in Spring} In the middle, we also learn about the configuration in Spring
💥The code is in the gitee repository💥The code used can be found here
🙏 Bo main also stay learn Learn rank paragraph , as if hair present ask topic , please Tell know , wrong often sense thank \textcolor{Orange} {blogger is also in the learning stage. If you find any problems, please let me know. Thank you very much} Bloggers are also in the learning stage. If you find any problems, please let us know. Thank you very much 💗

🐳 Click to send you to "a brief understanding of the theoretical derivation of Spring and IOC"

4, How IOC creates objects

1. Create objects using parameterless construction – default

  • <!--Parameterless construction is used by default-->
    <bean id="user" class="com.hxl.pojo.User">
        <property name="name" value="Wang Mumu"/>
    </bean>
    

2. Creating objects with parametric constructs (three methods)

  • <!--First, subscript assignment-->
    <bean id="user" class="com.hxl.pojo.User">
        <!--Here 0 represents the first parameter-->
        <constructor-arg index="0" value="Wang Mumu Sir"/>
    </bean>
    
  • <!--The second is to create by type,
        Not recommended because if there are two String The type will go wrong-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg type="java.lang.String" value="wangmumu"/>
    </bean>
    
  • <!--The third method: set directly through the parameter name-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg name="name" value="Wang Mumu"/>
    </bean>
    

Spring instantiated the bean when it was created. That is, as long as it is configured in the bean, it will be instantiated (creating a parameterless construction object) whether it is used or not

Summary: when the configuration file is loaded, the objects managed in the container have been initialized

code:

package com.hxl.pojo;

public class User {
    private String name;

    public User() {
        System.out.println("User No parameter structure!");
    }

    public User(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void show(){
        System.out.println(this.name);
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

mutually with real body class three species square type no can with Time Save stay Ha , remember have to send use of Time Wait notes Buddhism fall his he square type \textcolor{Magenta} {the three methods of the same entity class cannot exist at the same time. Remember to comment out the other methods when using} The three methods of the same entity class cannot exist at the same time. Remember to comment out the other methods when using them

<?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">
    <!--First, subscript assignment-->
    <bean id="user" class="com.hxl.pojo.User">
    <!--Here 0 represents the first parameter-->
       <constructor-arg index="0" value="Wang Mumu Sir"/>
    </bean>

    <!--The second is to create by type,-->
    <!--Not recommended because if there are two String The type will go wrong-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg type="java.lang.String" value="wangmumu"/>
    </bean>

    <!--The third method: set directly through the parameter name-->
    <bean id="user" class="com.hxl.pojo.User">
        <constructor-arg name="name" value="Wang Mumu"/>
    </bean>

</beans>
import com.hxl.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        //Spring container is similar to matchmaking website
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
}
//The following two methods can be implemented, one is strong rotation, the other is strong rotation
User user = (User) context.getBean("user");
User user = context.getBean("user", User.class);

5, Spring configuration

5.1 alias

<!--Alias: if an alias is added, we can also use the alias to get this object-->
<alias name="user" alias="userNew"/>

5.2 Bean configuration

<!--
    id:bean The unique identifier of the object, that is, the object name
    class:bean Fully qualified name corresponding to the object: package name+type
    name: It's also an alias,and name More advanced, you can take multiple aliases at the same time,Spaces and commas can be identified. There are three aliases below
    -->
<bean id="userT" class="com.hxl.pojo.User" name="user2 u1,u2"/>

If you do the above, the class will become UserT during the test

UserT user = (UserT) context.getBean("user");

5.3 import

This import is generally used for team development. It can import and merge multiple configuration files into one

Suppose there are multiple developers in the project, who are responsible for the development of different classes, and different classes need to be registered in different beans. We can use import to merge everyone's bean.xml into a total applicationContext.xml

<import resource="beans.xml"/>
public class MyTest {
    public static void main(String[] args) {
        //Spring container is similar to matchmaking website
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) context.getBean("user2");
        user.show();
    }
}

6, Dependency injection DI

1. Constructor injection

The previous hello is constructor injection

2.Set mode injection [ key ]

  • Dependency injection: Set injection!
    • Dependency: the creation of bean objects depends on the container
    • Injection: all attributes in the bean object are injected by the container

2.1 [ environment construction ]

1. Complex type

package com.hxl.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

2. Real test object

package com.hxl.pojo;

import java.util.*;

public class Student {
    private String name;
    //Reference type, and assign value with ref at that time
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

3.beans.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">

    <!--The first: normal value injection: value-->
    <bean id="student" class="com.hxl.pojo.Student">
        <property name="name" value="Wang Mumu"/>
    </bean>

</beans>

4. Testing

import com.hxl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
}

2.2 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="address" class="com.hxl.pojo.Address"/>


    <bean id="student" class="com.hxl.pojo.Student">
        <!--The first: normal value injection: value-->
        <property name="name" value="Wang Mumu"/>
        <!--Second, Bean Injection: ref-->
        <property name="address" ref="address"/>
        <!--Third, array injection-->
        <property name="books">
            <array>
                <value>The Dream of Red Mansion</value>
                <value>Water Margin</value>
            </array>
        </property>
        <!--Fourth: List injection-->
        <property name="hobbys">
            <list>
                <value>fall in love</value>
                <value>Knock code</value>
            </list>
        </property>
        <!--Fifth: Map-->
        <property name="card">
            <map>
                <entry key="ID" value="1254482515165451X"/>
                <entry key="bank card" value="1549413214151515485"/>
            </map>
        </property>
        <!--Sixth: Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>Glory of Kings</value>
            </set>
        </property>
        <!--Seventh: NULL-->
        <property name="wife">
            <null/>
        </property>
        <!--Eighth: Properties-->
        <property name="info">
            <props>
                <prop key="Student number">yj2021</prop>
                <prop key="full name">Wang Mumu</prop>
            </props>
        </property>
    </bean>
</beans>
import com.hxl.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
        /*
        * Student{name='Wang Mumu ', address=Address{address='null'}, books = [dream of Red Mansions, outlaws of the marsh], hobbys = [fall in love, knock the code],
        * card={Id = 12544825165451x, bank card = 15494132141515485}, games = [lol, King's glory], wire ='null ',
        *  info={Student number = yj2021, name = Wang Mumu}}

         * */
    }
}

Before running, remember to add the toString method in address and add address.toString() in toString in Student

3. Expansion mode injection

We can use the p namespace as well as the c namespace

Official interpretation

3.1 P namespace

  • You can directly inject the value of the property: property

Insert in xml

xmlns:p="http://www.springframework.org/schema/p"

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

    <!--p Namespace injection, you can directly inject the value of the attribute: property-->
    <bean id="user" class="com.hxl.pojo.User" p:name="Wang Mumu" p:age="23"/>

</beans>

3.2 c namespace injection

  • The value of the attribute can be injected through the constructor: construct args

Introducing in xml

xmlns:c="http://www.springframework.org/schema/c"

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

    <!--p Namespace injection, you can directly inject the value of the attribute: property-->
    <bean id="user" class="com.hxl.pojo.User" p:name="Wang Mumu" p:age="23"/>

    <!--c Namespace injection, you can inject the value of the attribute through the constructor: construct-args-->
    <bean id="user2" class="com.hxl.pojo.User" c:name="Wang Mumu s" c:age="23"/>

</beans>
  • Note that there must be a parameter structure in the entity class, otherwise an error will be reported. At the same time, there must be no parameter structure. If not, an error will be reported in the p namespace

3.3 testing

@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml");
        User user = (User) context.getBean("user2");
        System.out.println(user.toString());
    }
}

3.4 notes

The p namespace and c namespace cannot be used directly, and xml constraints need to be imported

4. Scope of bean

4.1 singleton mode

<bean id="user2" class="com.hxl.pojo.User" c:name="Wang Mumu s" c:age="23" scope="singleton"/>

User user = (User) context.getBean("user2",User.class);
User user2 = (User) context.getBean("user2",User.class);
System.out.println(user == user2);

Although there are two user s, they are taken from a single instance, that is, an entity class is created

Definitions that can be displayed are singletons by default

4.2 prototype mode

Each time you get from the container, a new object is generated.

<!--c Namespace injection, you can inject the value of the attribute through the constructor: construct-args-->
<bean id="user2" class="com.hxl.pojo.User" c:name="Wang Mumu s" c:age="23" scope="prototype"/>

Once you test the above code after using this, you will find that the result is false.

4.3 other request s, session s and Applications

These can only be used in web development

Posted by WDPEjoe on Wed, 17 Nov 2021 15:41:52 -0800