Spring IoC

I. IoC Container (Concept)

1. What is IoC?

  • Inversion of control, which gives Spring control over object creation and calls between objects
  • The purpose of using IoC is to reduce coupling

2. What technologies are used at the bottom of IoC?

  • XML parsing
  • The factory pattern
  • reflection

3. Spring provides two ways to implement the IoC container (two interfaces) :

  • BeanFactory interface: the basic implementation of IoC container, is the internal interface of Spring, not provided for developers to use (loading configuration file will not create objects, only when the object is back to create objects, lazy loading)
  • ApplicationContext: A subinterface of the BeanFactory interface that provides more powerful functionality and is typically used by developers (the configuration file object is created when the configuration file is loaded)

4. Implementation class of the ApplicationContext interface

  • FileSystemXmlApplicationContext: load the XML configuration file using the absolute path
  • ClassPathXmlApplicationContext: load the XML configuration file using a relative path, the SRC directory to the root directory

Ii. IoC container-bean Management (BASED on XML)

1. Bean management consists of two operations:

  • Spring creates objects
  • Spring injected properties

2. Create objects based on XML

  • When creating an object, the default is to execute the method of no argument construction to complete the object creation
<bean id="Id name, unique identifier of the Bean object" class="The full class name of the Bean object"></bean>
Copy the code

3. Inject attributes based on XML

  • DI: dependency injection ** (DI is a concrete implementation of IoC) **
  1. Use the set method for injection

    public class Book {
        // Create a property
        private String bname;
    
        // Create the set method corresponding to the attribute
        public void setBname(String bname) {
            this.bname = bname; }}Copy the code
    <bean id="book" class="com.atguigu.spring5.Book">
        <! Name: the name of the property in the class value: the value injected into the property -->
        <propert1y name="bname" value="Hello"></property>
        <property name="bauthor" value="World"></property>
    </bean>
    Copy the code
  2. Parameter constructor injection

    public class Orders {
        / / property
        private String oname;
        private String address;
        // There are arguments
        public Orders(String oname,String address) {
            this.oname = oname;
            this.address = address; }}Copy the code
    <bean id="orders" class="com.atguigu.spring5.Orders">
        <constructor-arg name="oname" value="Hello"></constructor-arg>
        <constructor-arg name="address" value="China!"></constructor-arg>
    </bean>
    Copy the code
  3. P namespace injection

    <! Add the p namespace to the configuration file header -->
    
            
    <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"		<!--Add a line herep-->
    
    	<! Insert a property into a bean tag -->
        <bean id="book" class="com.atguigu.spring5.Book" p:bname="hello" p:bauthor="world"></bean>
    </beans>
    Copy the code

4. XML injects other types of attributes

  • Injection of null values

    <property name="address">
        <null/>
    </property>
    Copy the code
  • Inject special symbols

    <! There are two ways to escape symbols: &lt; To replace <, use CDATA -->
    <property name = "address">
        <value><! [CDATA [< < Nanking > >]] ></value>
    </property>
    Copy the code

5. Inject properties: External beans

  • Create two classes, the Service class and the DAO class

  • Service invokes methods in dao

  • Do this in the Spring configuration file

    Public class UserDao {private UserDao UserDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void add() { System.out.println("service add..............." ); // Call the DAO method userdao.update (); Public class UserDaoImpl implements UserDao {@override public void update() {system.out.println ("dao ") update..........." ); }}
    Copy the code
  • Do this in the Spring configuration file

    <bean id="userService" class="com.atguigu.spring5.UserService">    <! Ref attribute: create userDao bean tag id value -->    <property name="userDao" ref="userDaoImpl"></property></bean><bean id="userDaoImpl" class="com.atguigu.spring5.UserDaoImpl"></bean>
    Copy the code

6. Inject properties: internal beans

  • One-to-many relationship: Departments and employees. One department has multiple employees, and one employee belongs to the same department

  • The one-to-many relationship between entity classes is represented, and the employee represents the department, which is represented by object type attributes

    Public class Dept {private String dname; public void setDname(String dname) { this.dname = dname; Public class Emp {private String ename; private String gender; // Employees belong to a certain department. 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; }}
    Copy the code
  • Configure it in the Spring configuration file

    <bean id="emp" class="com.atguigu.spring5.bean.Emp">    <! -- Set the value of the normal property -->    <property name="ename" value="Andy"></property>    <property name="gender" value="Female"></property>        <! Set the properties of the object type -->    <property name="dept">        <bean id="dept" name="com.atguigu.spring5.bean.Dept">            <property name="dname" value="Security Department"></property>        </bean>    </property></bean>
    Copy the code

7. Inject properties: Cascade assignments

  • Method 1: Cascade assignment

    <! -- Method 1: Cascade assignment --><bean id="emp" class="com.atguigu.spring5.bean.Emp">    <! Set two general 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="Public relations department."></property></bean>
    Copy the code
  • Generate the dept get method ** (must have get method) **

     <! -- Cascade assignment --><bean id="emp" class="com.atguigu.spring5.bean.Emp">    <! Set two general 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>
    Copy the code

8. XML injects collection attributes

  • Inject array type properties
  • Inject the List collection type attribute
  • Inject Map collection type attributes
  • Inject the Set collection type property
Public class Stu {//1 private String[] courses; Private list 
      
        list; private list 
       
         list; //3 Map collection type attribute private map 
        
          maps; Private set 
         
           sets; private set 
          
            sets; public void setSets(Set
           
             sets) { this.sets = sets; } public void setCourses(String[] courses) { this.courses = courses; } public void setList(List
            
              list) { this.list = list; } public void setMaps(Map
             
               maps) { this.maps = maps; }}
             ,>
            
           
          
         
        ,string>
       
      
Copy the code
<! -- (2) Configure in the Spring configuration file --><bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">    <! -- Array type property injection -->    <property name="courses">        <array>            <value>Java classes</value>            <value>Database course</value>        </array>    </property>    <! --list type attribute injection -->    <property name="list">        <list>            <value>Zhang SAN</value>            <value>Small three</value>        </list>    </property>    <! -- Map 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>
Copy the code

9. Set the object type value in the collection

  • If the element type in the collection is an object, it cannot be injected in the normal way

    Public class Course {private String cname; public void setCname(String cname) { this.cname = cname; } @Override public String toString() { return "Course{" + "cname='" + cname + '\'' + '}'; }}
    Copy the code
  • Then edit the XML configuration file

    <! Create course object --><bean id="course1" class="com.atguigu.spring5.collectiontype.Course">    <property name="cname" value="Spring5 framework"></property></bean><bean id="course2" class="com.atguigu.spring5.collectiontype.Course">    <property name="cname" value="MyBatis framework"></property></bean><! -- Then inject --> into the property<bean>    <property name="courseList">        <list>            <ref bean="course1"></ref>            <ref bean="course2"></ref>        </list>    </property></bean>
    Copy the code

Extract the injected parts of the collection

  • Start by mapping the namespace util into the Spring configuration file

    
            <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"       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"></beans>
    Copy the code
  • Use the util tag to complete the List collection injection extraction

    <util:list id="bookList">    <value>Yi jin jing</value>    <value>Nine Yin true through</value>    <value>Sunflower treasure dian</value></util:list>
    Copy the code
  • Inject the extracted collection type properties into use

    <bean id="book" class="com.atguigu.spring5.collectiontype.Book">    <property name="list" ref="bookList"></property></bean>
    Copy the code

11. FactoryBean

  • Spring beans come in two types: plain beans and factory Beans.

    • Plain beans: The bean type defined in the configuration is the return type

    • Factory Beans: Define bean types in configuration files that are different from return types

  • The first step is to create a class that acts as a FactoryBean and implements the interface FactoryBean

  • The second step is to implement the method in the interface and define the returned bean type in the implemented method

    public class MyBean implements FactoryBean<Course> {    Throws Exception {Course Course = new Course(); // Override public Course getObject() throws Exception {Course Course = new Course(); course.setCname("hhh"); return course; }}
    Copy the code
    <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean"></bean>
    Copy the code
    @Testpublic void test(a) {    ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");    Course Course = Context.getBean ("myBean", course.class); System.out.println(course); }
    Copy the code

12. Bean scope

  • In Spring, beans are singleton objects by default (they can also be multi-instance objects, but we need to configure them manually)

  • Setting single-instance or multi-instance:

    • There are properties in the Spring configuration file bean tagscopeTo set single-instance/multi-instance
    • Scope attributes have two values: Singleton (single instance, default) and Prototype (multi-instance)
    <! -- Set it to a multi-instance object --><bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype">        <property name="list" ref="bookList"></property></bean>
    Copy the code
  • Singleton and Prototype

    • Singleton instance, Prototype multi-instance
    • Setting scope to Singleton creates a singleton when the Spring configuration file is loaded. With a value of prototype, create multi-instance objects only when calling getBean (lazy)

13. Bean life cycle

  • What is the life cycle: the process from object creation to destruction

  • Bean life cycle:

    1. Create bean instance through constructor (no-parameter construction)

    2. Set values for bean properties and references to other beans (set method)

    3. Call the bean’s initialization method (configuration initialization method required)

    4. You’ve got the object and you’re ready to use it

    5. When the container is closed, the bean’s destruction method is called, at which point the object is destroyed (configuration destruction method is required)

    public class Orders {    private String oname;        // No argument construct public Orders() {system.out.println (" the first step is to execute the no-argument construct to create the bean instance "); } public void setOname(String oname) { this.oname = oname; System.out.println(" Call the set method in the second step to set the property value "); } public void initMethod() {system.out.println (" the third step of the initialization method "); } public void destroyMethod() {system.out.println (" fifth destroyMethod "); }}
    Copy the code
    <bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">    <property name="oname" value="Mobile phone"></property></bean>
    Copy the code
     @Test public void testBean3(a) {	ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");	Orders orders = context.getBean("orders", Orders.class);	System.out.println("Step 4 Get the create bean instance object");	System.out.println(orders); 	/ / manual for the bean instance destruction, need downward transition (ClassPathXmlApplicationContext applicationContext). The close (); }
    Copy the code
  • The normal life cycle has five steps, and if a rear processor is configured, it has seven steps

    1. Create bean instance through constructor (no-parameter construction)
    2. Set values for bean properties and references to other beans (set method)
    3. = = the bean bean instance transfer method of post processor (postProcessBeforeInitialization) = =
    4. Call the bean’s initialization method (configuration initialization method required)
    5. = = the bean bean instance transfer method of post processor (postProcessAfterInitialization) = =
    6. You’ve got the object and you’re ready to use it
    7. When the container is closed, the bean’s destruction method is called, at which point the object is destroyed (configuration destruction method is required)
  • Configure the backend handler (this applies to all beans in the configuration file if the backend handler is configured) :

    // Create a post-processor implementation class, MyBeanPost implements BeanPostProcessor {@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; }}
    Copy the code
    <bean id="myBeanPost" class="com.atguigu.spring5.bean.MyBeanPost"></bean>
    Copy the code

14. Automatic assembly

  • What is auto-assembly?

    • Spring automatically injects matching properties based on the specified assembly rule (property name or property type)
  • Implement automatic assembly process

    • The bean label property autowire configures autowire

    • Two common values for autowire:

      • ByName: Automatic injection based on the property name. The id of the injected bean should be the same as the class property name

      • ByType: Inject ** (cannot have two beans of the same type) ** based on the property type

    1. Automatic injection based on the property name

      <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">	<! --<property name="dept" ref="dept"></property>--></bean><bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>
      Copy the code
    2. Automatic injection based on the property type

      <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">	<! --<property name="dept" ref="dept"></property>--></bean><bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>
      Copy the code

15. External properties files

  • Configure the database information directly

    1. Configure the Druid connection pool
    2. Importing jar packages that druid depends on
    <! 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/study"></property>    <property name="username" value="root"></property>    <property name="password" value="root"></property></bean>
    Copy the code
  • Import an external properties file to configure the database connection pool

    1. Create external properties file, properties format file, write connection using database information

      driverClass=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/studyusername=rootpassword=root
      Copy the code
    2. Introduce the external properties properties 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">    	<! Import external properties files with tags -->    <context:property-placeholder location="classpath:jdbc.properties"/>    <! -- Configure connection pool -->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">        <property name="driverClassName" value="${driverClass}"></property>        <property name="url" value="${url}"></property>        <property name="username" value="${userName}"></property>        <property name="password" value="${password}"></property>    </bean></beans>
      Copy the code