Spring learning - IOC container

Keywords: Java Spring IDEA

2.IOC container

1.IOC container

1. What is IOC (control reversal)

(1) leave the object creation and the calling process between objects to Spring for management
(2) purpose of using IOC: to reduce the coupling degree
(3) People's case is IOC implementation

2.IOC underlying principle

xml parsing, factory schema, reflection

(1) .xml parsing

xml configuration file to configure the created object

<bean id=" " class=" "></bean>
(2) . factory mode

Define an intermediate static function to reduce its coupling

(3) . reflection

Create objects by reflection

Class xx=Class.forName(classValue);
xx.newInstance();

3. Draw pictures to explain the underlying principle of IOC

4.IOC interface

1. The IOC idea is based on the IOC container, and the bottom layer of the IOC container is the object factory
2. Two methods (two interfaces) of IOC container implementation provided by spring

(1) BeanFactory interface: the basic implementation of IOC container is the use interface of Spring internal interface, which is not provided to developers for use (objects will not be created when loading configuration files, but will be created when obtaining objects.)

(2) ApplicationContext interface: 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!

3. Implementation class of ApplicationContext interface

2.IOC container Bean management

1. What is Bean management

(0) Bean management consists of two operations:
(1) Spring creates objects;
(2) Spring injection attribute;

2. There are two ways to manage beans

(1) Implementation of configuration mode based on XML configuration file
(2) Annotation based implementation

3.IOC operation Bean management

1. Create objects based on XML configuration files
<!--to configure User objects creating-->
<bean id="user" class="com.lhl.Spring5.User"></bean>

(1) In the Spring configuration file, you can create objects by using bean tags and adding corresponding attributes to the tags
(2) There are many properties in the bean tag. Introduce the common properties

*id attribute: unique attribute

*Class attribute: the full path of the class (package class path)

(3) When creating an object, the parameterless construction method is also executed by default

2. Inject attributes based on XML

1.DI: dependency injection (injection attribute)
set mode injection

(1) Traditional way:
1) Create a class, define properties and corresponding set methods

public class Book {

  //Create attribute
  private String bname;

  private String bauthor;
  //Create the set method corresponding to the property
  public void setBname(String bname) {
    this.bname = bname;
  }

  public void setBauthor(String bauthor) {
    this.bauthor = bauthor;
  }

2) Create a configuration object in the spring configuration file and configure attribute injection

<!--set Method injection properties-->
<bean id="book" class="com.lhl.Spring5.Book">
  <!-- use property Complete attribute injection
   name:The name of the attribute in the class
   value:The value injected into the attribute
   -->
  <property name="bname" value="sun"></property>
  <property name="bauthor" value="moon"></property>
</bean>

3) Testing

  @Test
  public void testBook() {
//1. Load the spring configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    Book book = context.getBean("book", Book.class);

//2. Or objects created by its configuration
    System.out.println(book);
    book.testDemo();
  }

(2) Parametric constructor injection

1) Create a class, define an attribute, and create a parameter construction method corresponding to the attribute

public class Orders {

  private String oname;
  private String address;

  public Orders(String oname,String address) {
    this.oname = oname;
    this.address = address;
  }

2) Configure in the spring configuration file

<!--3.Parametric structure injection attribute-->
<bean id="orders" class="com.lhl.Spring5.Orders">
  <constructor-arg name="oname" value="stayreal"></constructor-arg>
  <constructor-arg name="address" value="China"></constructor-arg>
</bean>

3) Testing

 @Test
  public void testOrders() {
//1. Load the spring configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    Orders orders = context.getBean("orders", Orders.class);

//2. Or objects created by its configuration
    System.out.println(orders);
    orders.ordersTest();

  }

(3) p namespace injection (understand)

1) Using p namespace injection can simplify xml based configuration

<!--1,add to p Namespace in profile header-->
<?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" 
 <!--Add a line here p-->

<!--2,stay bean Tag for attribute injection set Mode injection (simplified operation)-->
<bean id="book" class="com.atguigu.spring5.Book" p:bname="very" p:bauthor="good">
</bean>
3.xml injection of other types of attributes

(1) Literal quantity
1) null value

<!-- null value  -->>
<property name="address" >
  <null/>
</property>

2) Property contains special symbols

<!-- 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>
4. Injection attribute - External bean

(1) Create two classes, service and dao
(2) Call the method in dao in service

public class UserService {

//  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.");

//  Create UserDao's object in the original way
//    UserDao userDao = new UserDaoImpl();
    userDao.update();

  }

(3) Configure in the spring configuration file

<!--1.service and dao Formation creation-->
<bean id="userService" class="com.lhl.Spring5.service.UserService">

  <!--  injection userDao object
  name Attribute value:Property name in class
  ref Attribute value:establish userDao object bean Object label id value
  -->
  <property name="userDao" ref="userDaoImpl"></property>


</bean>
<bean id="userDaoImpl" class="com.lhl.Spring5.dao.UserDaoImpl"></bean>
5. Injection attribute - nebulabean and cascade assignment

(1) One to many relationships: departments and employees
A department has multiple employees, and an employee belongs to a department (the Department is one and the employees are many)
(2) 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 the form of objects
  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;
  }

(3) Configure in the spring configuration file

<!-- inside bean -->
<bean id="emp" class="com.lhl.Spring5.bean.Emp">
  <!--  Set two common properties  -->
  <property name="eName" value="lhl"></property>
  <property name="gender" value="male"></property>
  <!--Set object type properties-->
  <property name="dept">
    <bean id="dept" class="com.lhl.Spring5.bean.Dept">
      <property name="dname" value="baidu"></property>

    </bean>
  </property>

</bean>
6. Injection attribute - cascade assignment

(1) The first way to write

<!-- Cascade assignment -->
<bean id="emp" class="com.lhl.Spring5.bean.Emp">
  <!--  Set two common properties  -->
  <property name="eName" value="lhl"></property>
  <property name="gender" value="male"></property>
  <!--Cascade assignment-->
  <property name="dept" ref="dept"></property>

</bean>
<bean id="dept" class="com.lhl.Spring5.bean.Dept">
  <property name="dname" value="huawei"></property>
</bean>

(2) The second way to write

 private Dept dept;
//  get method for generating dept


  public Dept getDept() {
    return dept;
  }
<!-- Cascade assignment -->
<bean id="emp" class="com.lhl.Spring5.bean.Emp">
  <!--  Set two common properties  -->
  <property name="eName" value="lhl"></property>
  <property name="gender" value="male"></property>
  <!--Cascade assignment-->
  <property name="dept" ref="dept"></property>
  <property name="dept.dname" value="jindong"></property>

</bean>
<bean id="dept" class="com.lhl.Spring5.bean.Dept">
  <property name="dname" value="huawei"></property>
</bean>
7.IOC operation Bean management - xml injection collection attribute

1. Inject attributes of array type
2. Inject List collection type attribute
3. Inject Map set type
(1) Create classes, define array, list, map and set type attributes, and generate corresponding set methods

public class Stu {
  //1. Create array type attribute
  private String[] courses;
  //2. Create List collection type attribute
  private List<String> list;
  //3. Create attributes of Map collection type
  private Map<String, String> maps;
  //4. Create attributes of Set collection type
  private Set<String> sets;
  

  public void setSets(Set<String> sets) {
    this.sets = sets;
  }


  public void setList(List<String> list) {
    this.list = list;
  }

  public void setMaps(Map<String, String> maps) {
    this.maps = maps;
  }


  public void setCourses(String[] courses) {
    this.courses = courses;
  }


}

(2) Configure in the spring configuration file

<!-- 1.Collection type attribute injection -->
<bean id="stu" class="com.lhl.Spring5.CollectionType.Stu">
  <!-- Array type attribute injection -->
  <property name="courses">
    <array>
      <value>java</value>
      <value>c++</value>
    </array>
  </property>
  <!-- list Type attribute injection -->
  <property name="list">
    <list>
      <value>lhl</value>
      <value>lll</value>
    </list>
  </property>
  <!-- maps Type attribute injection -->
  <property name="maps">
    <map>
      <entry key="JAVA" value="java"></entry>
      <entry key="C++" value="c++"></entry>
    </map>
  </property>
  <!-- sets Type attribute injection -->
  <property name="sets">
    <set>
      <value>MySql</value>
      <value>Redis</value>
    </set>
  </property>


</bean>
8. Set the object type value in the collection
<!--  Create multiple course object-->
  <bean id="course1" class="com.lhl.spring5.collectiontype.Course">
    <property name="cname" value="Spring frame"></property>

  </bean>
  <bean id="course2" class="com.lhl.spring5.collectiontype.Course">
    <property name="cname" value="Django frame"></property>

  </bean>








<!--  injection List Collection object, value is object  -->

    <property name="courseList">

      <list>

        <ref bean="course1"></ref>
        <ref bean="course2"></ref>

      </list>

    </property>
9. Extract the set injection part

(1) Introducing the namespace util into the spring 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"
       xmlns:p="http://www.springframework.org/schema/p"
       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>

(2) Use util tag to complete list collection injection and extraction

<!--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.lhl.spring5.collectiontype.Book" scope="prototype">
  <property name="list" ref="bookList"></property>
</bean>

Posted by Natty_Dreadlock on Mon, 20 Sep 2021 10:21:19 -0700