Spring IOC container - Bean management - super detailed explanation based on XML!!!

Posted by benracer on Sun, 19 Dec 2021 22:09:34 +0100

Spring IOC container - Bean management - based on XML 🎈🎈🎈

Spring framework overview

  1. Spring is a lightweight open source Java EE framework
  2. Spring can solve the complexity of enterprise application development
  3. Spring has two core parts: IOC and AOP
    • IOC: inversion of control, leaving the process of creating objects to Spring for management
    • AOP: aspect oriented, without modifying the source code for function enhancement
  4. Spring features
    1. Convenient decoupling and simplified development
    2. AOP programming support
    3. Convenient program testing
    4. Facilitate integration with other frameworks
    5. Facilitate transaction operations
    6. Reduce the difficulty of API development

IOC concept and principle

  1. What is IOC?

    • Control inversion, and leave the object creation and calling process between objects to Spring for management
    • Purpose of using IOC: to reduce coupling
  2. IOC underlying principle

    • xml parsing, factory schema, reflection
  3. Graphic IOC underlying principle

  1. IOC (BeanFactory interface)

    1. The IOC idea is based on the IOC container, and the bottom layer of the IOC container is the object factory

    2. Spring provides two ways to implement IOC container: (two interfaces)

      â‘  BeanFactory: the basic implementation of IOC container is the internal use interface of Spring. It does not provide developers to use it. Objects will not be created when loading configuration files. Objects are created only after obtaining (using) objects

      â‘¡ ApplicationContext: the sub interface of BeanFactory interface, which provides more and more powerful functions for developers to use (the configuration file object will be created when loading the configuration file). It is recommended to use!

  2. IOC operation Bean management

    1. What is Bean management?

      Bean management refers to two operations:

      1. Spring create object
      2. Spring injection properties
    2. Two ways of Bean management operations

      1. Implementation of configuration file based on xml
      2. Annotation based implementation

The next section explains in detail the IOC operation Bean management based on XML

IOC operation Bean Management (set injection & & injection using parametric structure)

  1. set mode injection

    â‘  Create a class, define properties and corresponding set methods

    public class Book {
        private String bName;
        private String bAuthor;
    	//Create attribute
        public void setbName(String bName) {
            this.bName = bName;
        }
    	//Create the set method corresponding to the property
        public void setbAuthor(String bAuthor) {
            this.bAuthor = bAuthor;
        }
    }
    

    â‘¡ Create a configuration object in the spring configuration file and configure attribute injection

     <!--use set Method injection properties-->
    <bean id="book" class="com.atguigu.spring5.testDemo.Book">
        <!--use property Complete attribute injection
                name: Attribute name in class
                value: Values injected into attributes
            -->
        <property name="bAuthor" value="snowlike hair"></property>
        <property name="bName" value="Jay Chou"></property>
    </bean>
    
  2. Injection using parameterized constructs

    â‘  Create a class and define an attribute. The created attribute corresponds to a parameter construction method

    public class Order {
        private String oName;
        private String address;
    
        public Order(String oName, String address) {
            this.oName = oName;
            this.address = address;
        }
    }
    

    â‘¡ Configure in the spring configuration file

    <!--Injection attribute with parameter construction-->
    <bean id="order" class="com.atguigu.spring5.testDemo.Order">
        <constructor-arg name="address" value="Dongfeng break"/>
        <constructor-arg name="oName" value="Jay Chou"/>
    </bean>
    

IOC operation Bean Management (xml injection and other types of attributes)

  1. Inject null values and special symbols

    <bean id="book" class="com.atguigu.spring5.Book">
        <!--(1)null value-->
        <property name="address">
            <null/><!--Add one in the attribute null label-->
        </property>
        
        <!--(2)Special symbol assignment-->
         <!--Attribute values contain special symbols
           a hold<>Escape &lt; &gt;
           b Write content with special symbols to CDATA
          -->
            <property name="address">
                <value><![CDATA[<<Nanjing>>]]></value>
            </property>
    </bean>
    
  2. Injection properties - External bean s

    â‘  Create two classes, service and dao

    public class UserService {//service class
    
        //Create UserDao type attribute and generate set method
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        public void add() {
            System.out.println("service add...............");
            userDao.update();//Call dao method
        }
    }
    
    public class UserDaoImpl implements UserDao {//dao class
    
        @Override
        public void update() {
            System.out.println("dao update...........");
        }
    }
    

    â‘¡ Configure in the spring configuration file

    <!--1 service and dao objects creating-->
    <bean id="userService" class="com.atguigu.spring5.service.UserService">
        <!--injection userDao object
            name Attribute: the name of the attribute in the class
            ref Properties: Creating userDao object bean label id value
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>
    
  3. Injection properties - internal bean s

    â‘  One to many relationships are represented between entity classes. Employees represent their departments and are represented by object type attributes

    //Department category
    public class Dept {
        private String dname;
        public void setDname(String dname) {
            this.dname = dname;
        }
    }
    
    //Employee category
    public class Emp {
        private String ename;
        private String gender;
        //Employees belong to a department and are represented in object form
        private Dept dept;
        
        public void setDept(Dept dept) {
            this.dept = dept;
        }
        public void setEname(String ename) {
            this.ename = ename;
        }
        public void setGender(String gender) {
            this.gender = gender;
        }
    }
    

    â‘¡ Configure in the spring configuration file

    <!--inside bean-->
    <bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <!--Set two common properties-->
        <property name="ename" value="Jay Chou"></property>
        <property name="gender" value="male"></property>
        <!--Set object type properties-->
        <property name="dept">
            <bean id="dept" class="com.atguigu.spring5.bean.Dept"><!--inside bean assignment-->
                <property name="dname" value="Publicity Department"></property>
            </bean>
        </property>
    </bean>
    
  4. Injection attribute - cascade assignment

    <!--Method 1: cascade assignment-->
    <bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <!--Set two common properties-->
        <property name="ename" value="Andy"></property>
        <property name="gender" value="female"></property>
        <!--Cascade assignment-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.atguigu.spring5.bean.Dept">
        <property name="dname" value="departments of public relations"></property>
    </bean>
    
     //Method 2: generate the get method of dept (the get method must have!!)
    public Dept getDept() {
        return dept;
    }
    
     <!--Cascade assignment-->
    <bean id="emp" class="com.atguigu.spring5.bean.Emp">
        <!--Set two common properties-->
        <property name="ename" value="jams"></property>
        <property name="gender" value="male"></property>
        <!--Cascade assignment-->
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="Technical department"></property>
    </bean>
    <bean id="dept" class="com.atguigu.spring5.bean.Dept">
    </bean>
    

IOC operation Bean Management (xml injection collection attribute)

  1. xml injection array type attribute
  2. xml injection List collection type attribute
  3. xml injection Map collection type attribute
//(1) Create classes, define array, list, map and set type attributes, and generate corresponding set methods
public class Stu {
    //1 array type properties
    private String[] courses;
    //2 list collection type attribute
    private List<String> list;
    //3 map collection type attribute
    private Map<String,String> maps;
    //4 set set type attribute
    private Set<String> sets;
    
    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

<!--(2)stay spring Configuration file-->
    <bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">
        <!--Array type attribute injection-->
        <property name="courses">
            <array>
                <value>java curriculum</value>
                <value>Database course</value>
            </array>
        </property>
        <!--list Type attribute injection-->
        <property name="list">
            <list>
                <value>Zhang San</value>
                <value>the other woman</value>
            </list>
        </property>
        <!--map Type attribute injection-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set Type attribute injection-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
</bean>

Set the object type value in the collection

//Students learn many courses
private List<Course> courseList;//Create collection
public void setCourseList(List<Course> courseList) {
    this.courseList = courseList;
}
<!--Create multiple course object-->
<bean id="course1" class="com.atguigu.spring5.collectiontype.Course">
    <property name="cname" value="Spring5 frame"></property>
</bean>
<bean id="course2" class="com.atguigu.spring5.collectiontype.Course">
    <property name="cname" value="MyBatis frame"></property>
</bean>

<!--injection list Collection type, value is object-->
<property name="courseList">
    <list>
        <ref bean="course1"></ref>
        <ref bean="course2"></ref>
    </list>
</property>
<!--Step 1: in spring Introducing namespaces into configuration files util-->
<?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:util="http://www.springframework. Org / schema / util "<! -- add util namespace -- >
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework. org/schema/util  http://www.springframework.org/schema/util/spring-util.xsd "> <! -- add util namespace -- >

<!--Step 2: use util Label complete list Set injection extraction-->
<!--Extract the set injection part-->
<!--1 extract list Collection type attribute injection-->
<util:list id="bookList">
    <value>Yi Jin Jing</value>
    <value>The nine Yin manual</value>
    <value>nine men's power</value>
</util:list>

<!--2 extract list Collection type attribute injection usage-->
<bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype">
    <property name="list" ref="bookList"></property>
</bean>

IOC operation Bean Management (FactoryBean)

  1. Spring has two types of beans, a normal bean and a factory bean

  2. Ordinary bean: the bean type defined in the configuration file is the return type

  3. Factory bean: the bean type defined in the configuration file can be different from the return type

    (1) Create a class that acts as a factory bean and implements the interface FactoryBean.

    (2) The second step is to implement the methods in the interface and define the returned bean type in the implemented methods.

    public class MyBean implements FactoryBean<Course> {
    
        //Define return bean
        @Override
        public Course getObject() throws Exception {
            Course course = new Course();
            course.setCname("abc");
            return course;
        }
    }
    
    <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
    </bean>
    
    @Test
    public void test3() {
     ApplicationContext context =
     new ClassPathXmlApplicationContext("bean3.xml");
     Course course = context.getBean("myBean", Course.class);//The return value type may not be the defined bean type!
     System.out.println(course);
    }
    

IOC operation bean Management (bean scope)

In Spring, by default, bean s are single instance objects. The scope is set as follows:

  1. In the bean tag of spring configuration file, there is a property (scope) to set single instance or multiple instances.

  2. scope property value

    • The first value: the default value, singleton, indicates that it is a single instance object.
    • The second value: prototype, indicates that it is a multi instance object.
    <bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype"><!--Set to multi instance-->
            <property name="list" ref="bookList"></property>
    </bean>
    
  3. Differences between singleton and prototype:

    • singleton single instance, prototype multi instance.
    • When the scope value is set to singleton, a single instance object will be created when the spring configuration file is loaded. When the scope value is set to prototype, the object is not created when loading the spring configuration file, and the multi instance object is created when calling the getBean method.

IOC operation bean Management (bean lifecycle)

  1. Lifecycle: the process from object creation to object destruction.

  2. bean lifecycle

    â‘  Create bean instance through constructor (no parameter construction)

    â‘¡ Set values for bean properties and references to other beans (call the set method)

    â‘¢ Call the initialization method of the bean (the method that needs configuration initialization)

    â‘£ The bean is ready to use (the object is obtained)

    ⑤ When the container is closed, call the bean destruction method (the method that needs to be configured for destruction)

  3. Demonstrates the bean lifecycle

    public class Orders {
        //Nonparametric construction
        public Orders() {
            System.out.println("First step---Perform parameterless construction creation bean example");
        }
        private String oname;
        public void setOname(String oname) {
            this.oname = oname;
            System.out.println("Step 2---call set Method to set the property value");
        }
        //Method for creating and executing initialization
        public void initMethod() {
            System.out.println("Step 3---Method of performing initialization");
        }
        //Method for creating and executing destruction
        public void destroyMethod() {
            System.out.println("Step 5---Method of performing destruction");
        }
    }
    
    <bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oName" value="Jay Chou">
        </property>
    </bean>
    
    @Test
    public void test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("Step 4---Get create bean Instance object");
        System.out.println(orders);
        ((ClassPathXmlApplicationContext)context).close();
    }
    
    Output:
    First step---Perform parameterless construction creation bean example
     Step 2---call set Method to set the property value
     Step 3---Method of performing initialization
     Step 4---Get create bean Instance object
    com.atguigu.spring5.bean.Orders@3c6f6d
     Step 5---Method of performing destruction
    
  4. The post processor of a bean. The bean life cycle has seven steps

    â‘  Create bean instance through constructor (no parameter construction)

    â‘¡ Set values for bean properties and references to other beans (call the set method)

    â‘¢ Pass the bean instance to the bean post processor's method postProcessBeforeInitialization

    â‘£ Call the initialization method of the bean (the method that needs configuration initialization)

    ⑤ Pass the bean instance to the bean post processor method postProcessAfterInitialization

    â‘¥ The bean is ready to use (the object is obtained)

    ⑦ When the container is closed, call the bean destruction method (the method that needs to be configured for destruction)

  5. Demonstrate the effect of adding a post processor

    (1) Create a class, implement the interface BeanPostProcessor, and create a post processor.

    public class MyBeanPost implements BeanPostProcessor {//Create post processor implementation class
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("Method executed before initialization");
            return bean;
        }
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("Method executed after initialization");
            return bean;
        }
    }
    

    (2) Configure post processor

    <!--Configuration file bean Parameter configuration-->
    <bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">	<!--Configure initialization method and destruction method-->
        <property name="oname" value="mobile phone"></property><!--This is through set Assignment method (injection attribute)-->
    </bean>
    
    <!--Configure post processor-->
    <bean id="myBeanPost" class="com.atguigu.spring5.bean.MyBeanPost"></bean>
    

IOC operation Bean Management (XML Automatic Assembly)

  1. What is automatic assembly?

    • Spring automatically annotates the matching attribute values according to the specified assembly rules (attribute name or attribute type)
  2. Demonstrate the automatic assembly process

    â‘  Auto injection based on attribute name

    <!--Realize automatic assembly
       bean Label properties autowire,Configure auto assembly
       autowire Property has two common values:
       byName Inject value according to attribute name bean of id The value is the same as the class attribute name
       byType Injection according to attribute type
      -->
    <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">
    </bean>
    <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>
    

    â‘¡ Auto injection based on attribute type

    <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">
    </bean>
    <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>
    

IOC operation Bean Management (external property file)

  1. Configure database information directly

    â‘  Configure Druid connection pool.

    â‘¡ Introduce Druid connection pool dependent jar package.

    <!--Configure connection pool directly-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    
  2. Importing an external property file to configure the database connection pool

    â‘  Create external property files, properties format files, and write database information (jdbc.properties)

    prop.driverClass=com.mysql.jdbc.Driver
    prop.url=jdbc:mysql://localhost:3306/userDb
    prop.userName=root
    prop.password=root
    

    â‘¡ Introduce the external properties property file into the spring configuration file -- introduce the context namespace.

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                               http://www.springframework. org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd "> <! -- introduce context namespace -- >
        
            <!--Import external properties file-->
        <context:property-placeholder location="classpath:jdbc.properties"/>
    
        <!--Configure connection pool-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${prop.driverClass}"></property>
            <property name="url" value="${prop.url}"></property>
            <property name="username" value="${prop.userName}"></property>
            <property name="password" value="${prop.password}"></property>
        </bean> 
    </beans>
    

Finally, don't forget to click three times 🎈🎈🎈

Topics: Java Spring xml Interview bean