Spring5 framework learning notes

Learning notes of Spring 5 framework (I)

1, Spring5 framework overview

  1. Spring is a lightweight open source JavaEE 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, function enhancement without modifying the source code
  4. Spring features

    • Convenient decoupling and simplified development
    • Aop programming support
    • Convenient program testing
    • Facilitate integration with other frameworks
    • Facilitate transaction operations
    • Reduce the difficulty of API development

2, IOC container

1. Underlying principle

  1. What is IOC?

    • Control inversion, and leave the process of object creation and calling between objects to Spring for management

    • Purpose of using IOC: to reduce coupling

    • public class testAdd {
        @Test
        public void testAdd(){
          ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
          User user = context.getBean("user", User.class);
          System.out.println(user);
          user.add();
        }
      }
      
  2. The underlying principle of IOC: xml parsing, factory mode, reflection. The IOC idea is based on the IOC container. The underlying layer of the IOC container is the object factory

  3. Spring provides two ways to implement IOC containers: (two interfaces)

    • BeanFactory: the basic implementation of IOC container is the internal use interface of Spring, which does not provide developers to use (objects will not be created when loading configuration files, and objects will be created only after obtaining (using) objects).
    • ApplicationContext: the sub interface of BeanFactory interface, which provides more and more powerful functions, is generally used by developers. (the object in the configuration file will be created when the configuration file is loaded)

2. Bean management XML method (I)

  1. What is bean Management: 1. Bean management refers to two operations. 2. Spring creates objects. 3. Spirng injects attributes

  2. There are two ways to manage beans: 1. Based on xml configuration file; 2. Based on annotation

  3. Create objects based on xml:

    • In the spring configuration file, you can create objects by using bean tags and adding corresponding attributes to the tags
    • There are many attributes in the bean tag. Introduce the commonly used attributes, * id attribute: unique identification* Class attribute: full path of class (package classpath)
    • When creating an object, the default is to execute the parameterless construction method to complete the object creation
  4. Inject attributes based on xml: DI: dependency injection, that is, inject attributes

  5. The first injection method: use the set method to inject:

    • (1) Create classes, define attributes and corresponding set methods

    • public class Book {
        private String bname;
        private String bauthor;
        public void setBname(String bname) {
          this.bname = bname;
        }
        public void setBauthor(String bauthor) {
          this.bauthor = bauthor;
        }
        public  void test_demo(){
          System.out.println(bname+"::"+bauthor);
        }
      }
      
    • (2) In the spring configuration file, configure the creation of configuration objects and configure attribute injection

    • <bean id="book" class="com.cgg.spring5.chapter1.Book">
        <property name="bname" value="Yi Jin Jing"></property>
        <property name="bauthor" value="Bodhidharma ancestor"></property>
      </bean>
      
  6. The second injection method: use parametric structure for injection:

    • (1) Create classes, define attributes, and create attributes corresponding to parameter construction methods

    • public class Order {
      
        private String oname;
        private String oaddress;
      
        public Order(String oname, String oaddress) {
          this.oname = oname;
          this.oaddress = oaddress;
        }
      }
      
    • (2) Configure in the spring configuration file

    • <bean id="order" class="com.cgg.spring5.chapter1.Order">
        <constructor-arg name="oname" value="computer"></constructor-arg>
        <constructor-arg name="oaddress" value="China"></constructor-arg>
      </bean>
      
  7. p namespace injection (understand): Using p namespace injection can simplify xml based configuration

    • The first step is to add the p namespace in the configuration file

    • <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">
      
    • The second step is to inject attributes and operate in the bean tag

    • <bean id="book" class="com.cgg.spring5.chapter1.Book" p:bname="The Nine Yang Manual" p:bauthor="anonymous person">
      </bean>
      
  8. xml injection other types of attributes:

    • null value:

    • <property name="address">
       <null/>
      </property>
      
    • The attribute value contains special symbols: 1. Escape < > 2. Write the content with special symbols to CDATA

  9. Injection attribute - External bean: 1. Create two classes, service class and dao class. 2. Call methods in dao in service. 3. Configure in spring configuration file

    • 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....");
          userDao.updata();
        }
      }
      
    • <bean id="userService" class="com.cgg.spring5.chapter1.UserService">
        <!--injection userDao object
          name Attribute: attribute name in the class
          ref Attributes: Creating userDao object bean label id value
        -->
        <property name="userDao" ref="userDaoImpl"></property>
      </bean>
      <bean id="userDaoImpl" class="com.cgg.spring5.chapter1.UserDaoImpl"></bean>
      
  10. Injection attribute - internal bean:1. One to many relationship: Department and employee. A department has multiple employees, an employee belongs to a department. Department is one, and employees are many. 2. Represent the one to many relationship between entity classes, employees represent the Department, and use the object type attribute for presentation

    • public class Dept {
        private String dname;
      
        public void setDname(String dname) {
          this.dname = dname;
        }
      
        @Override
        public String toString() {
          return "Dept{" +
              "dname='" + dname + '\'' +
              '}';
        }
      }
      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 setEname(String ename) {
          this.ename = ename;
        }
      
        public void setGender(String gender) {
          this.gender = gender;
        }
      
        public void setDept(Dept dept) {
          this.dept = dept;
        }
      
        public void print(){
          System.out.println(ename+"::"+gender+"::"+dept);
        }
      }
      
    • <!--inside bean-->
        <bean id="emp" class="com.cgg.spring5.chapter1.Emp">
      <!--  Set two general properties  -->
          <property name="ename" value="lucy"></property>
          <property name="gender" value="female"></property>
      <!--  Set object type properties  -->
          <property name="dept">
            <bean id="dept" class="com.cgg.spring5.chapter1.Dept">
              <property name="dname" value="Security Department"></property>
            </bean>
          </property>
        </bean>
      
    • Cascade assignment:

    • <!--  Cascade assignment-->
        <bean id="emp" class="com.cgg.spring5.chapter1.Emp">
          <!--  Set two general properties  -->
          <property name="ename" value="lucy"></property>
          <property name="gender" value="female"></property>
          <!--  Cascade assignment  -->
          <property name="dept" ref="dept"></property>
        </bean>
        <bean id="dept" class="com.cgg.spring5.chapter1.Dept">
          <property name="dname" value="Finance Department"></property>
        </bean>
      </beans>
      
  11. Inject array type attributes, list set type attributes, and * * map * * set type attributes: create classes, define array, list, map, and set type attributes, and generate corresponding set methods

    • public class Stu {
        //1 array type attribute
        private String[] courses;
        //2 list set type attribute
        private List<String> list;
        //3 map set type attribute
        private Map<String,String> maps;
        //4 set 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;
        }
      
        @Override
        public String toString() {
          return "Stu{" +
              "courses=" + Arrays.toString(courses) +
              ", list=" + list +
              ", maps=" + maps +
              ", sets=" + sets +
              '}';
        }
      }
      
    • <bean id="stu" class="com.cgg.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>
      
  12. Set the object type value in the collection:

    <!--injection list Collection type, value is object-->
        <property name="courseList">
          <list>
            <ref bean="course1"></ref>
            <ref bean="course2"></ref>
          </list>
        </property>
      </bean>
      <!--Create multiple course object-->
      <bean id="course1" class="com.cgg.spring5.collectiontype.Course">
      <property name="name" value="Spring5 frame"></property>
    </bean> 
      <bean id="course2" class="com.cgg.spring5.collectiontype.Course">
      <property name="name" value="MyBatis frame"></property>
    </bean>
    
  13. Use the util tag to complete the list set injection extraction:

    <?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">
    <!--  extract list Collection type attribute injection-->
      <util:list id="bookList">
        <value>Yi Jin Jing</value>
        <value>The Nine Yin Manual</value>
        <value>The Nine Yang Manual</value>
      </util:list>
      <bean id="book" class="com.cgg.spring5.collectiontype.Book">
        <property name="BookList" ref="bookList"></property>
      </bean>
    

3. Bean management

  1. Spring has two types of beans, a common bean and a FactoryBean

    • Ordinary bean: the bean type defined in the configuration file is the return type
    • Factory bean: the bean type defined in the configuration file can be different from the return type
  2. Factory bean:

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

    • 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 {
      
        @Override
        public boolean isSingleton() {
          return false;
      //    return FactoryBean.super.isSingleton();
        }
      
        @Override
        public Course getObject() throws Exception {
          Course course = new Course();
          course.setName("abc");
          return course;
        }
      
        @Override
        public Class<?> getObjectType() {
          return null;
        }
      }
      <bean id="myBean" class="com.cgg.spring5.FactoryBean.MyBean">
        </bean>
      public static void main(String[] args) {
          ApplicationContext context = new ClassPathXmlApplicationContext(
              "chapter11/bean3.xml");
          Course course = context.getBean("myBean", Course.class);
          System.out.println(course);
        }
      
  3. bean scope:

    1. In Spring, set whether to create bean instances as single instances or multiple instances
    2. In Spring, bean s are single instance objects by default
    3. How to set single instance or multi instance: 1. There is a property (scope) in the bean tag of spring configuration file to set single instance or multi instance. 2. scope property value:
      • The default value of the first value, singleton, indicates that it is a single instance object
      • The second value, prototype, represents a multi instance object
    4. The difference between singleton and prototype:
      • The first singleton single instance, prototype multi instance
      • Second, when the scope value is set to singleton, a single instance object will be created when loading the spring configuration file; 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
  4. bean lifecycle:

    1. Universal life cycle:

      • 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 requiring configuration initialization)

      • The bean is ready for use (the object is obtained)

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

      • public class Orders {

        //Parameterless construction
        public Orders() {
            System.out.println("The first step is to create a parameterless structure bean example");
        }
        
        private String oname;
        public void setOname(String oname) {
            this.oname = oname;
            System.out.println("Step 2 call set Method to set the attribute value");
        }
        
        //Create an initialization method for execution
        public void initMethod() {
            System.out.println("Step 3: execute the initialization method");
        }
        
        //Create the method of destruction performed
        public void destroyMethod() {
            System.out.println("Step 5 implement the destruction method");
        }
        }
        
    2. The post processor of 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)

      • The method of passing the bean instance to the bean post processor postProcessBeforeInitialization

      • Call the initialization method of the bean (the method requiring configuration initialization)

      • The method of passing the bean instance to the bean post processor postProcessAfterInitialization

      • The bean is ready for use (the object is obtained)

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

      • Create a class, implement the interface BeanPostProcessor, and create a post processor:

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

4. Bean management XML method (II)

  1. Automatic assembly: Spring automatically injects the matching attribute values according to the specified assembly rules (attribute name or attribute type)

    • Automatic injection according to attribute name

    • Automatic injection according to attribute type

    • <!--Realize automatic assembly
       bean Label properties autowire,Configure automatic assembly
       autowire Attribute usually has two values:
       byName Inject according to attribute name, inject value bean of id The value is the same as the class attribute name
       byType Inject according to attribute 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>
      
  2. Bean Management (external properties file):

    • Directly configure the database information: 1. Configure the Druid connection pool 2. Introduce the jar package that the Druid connection pool 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/userDb"></property>
       <property name="username" value="root"></property>
       <property name="password" value="root"></property>
      </bean>
      
    • Import an external property file to configure the database connection pool: 1. Create an external property file, properties format file, and write database information. 2. Import the external properties property file into the spring configuration file * import the context namespace

    • Using tags to import external property files in spring configuration files

    • <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" 
       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/util 
      http://www.springframework.org/schema/util/spring-util.xsd 
       http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd">
      <!--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>
      

5. Bean Management (based on annotation):

  1. What is annotation: 1. annotation is a special mark of code, format: @ annotation name (attribute name = attribute value, attribute name = attribute value...) 2. Using annotation, annotation acts on classes, methods and attributes. 3. Purpose of using annotation: to simplify xml configuration

  2. Spring provides annotations for creating objects in Bean Management:

    • @Component
    • @Service
    • @Controller
    • @Repository
    • *The above four annotation functions are the same, and can be used to create bean instances
  3. Turn on component scanning:

      <!--Turn on component scanning
     1 If multiple packages are scanned, they are separated by commas
     2 Scan package upper directory
    -->
      <context:component-scan base-package="com.cgg.spring5"></context:component-scan>
    

    Create a class and add the create object annotation on it:

    @Service(value = "userService1")//<bean id="userService" class=".."/>
    public class UserService1 {
      public void add() {
        System.out.println("service add.......");
      }
    }
    

    Component scanning details configuration:

    <!--Example 1
     use-default-filters="false" Indicates that the default is not used now filter,Configure yourself filter
     context:include-filter ,Set what to scan
    --><context:component-scan base-package="com.atguigu" use-defaultfilters="false">
     <context:include-filter type="annotation" 
     
    expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--Example 2
     Next, configure all contents of the scanning package
     context:exclude-filter:  Set what is not scanned
    --><context:component-scan base-package="com.atguigu">
     <context:exclude-filter type="annotation" 
     
    expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
  4. Implement attribute injection based on annotation:

    1. @Autowired: automatically assemble according to the attribute type:

      • The first step is to create the service and dao objects, and add the creation object annotation in the service and dao classes

      • The second step is to inject dao objects into the service, add dao type attributes to the service class, and use annotations on the attributes

      • @Service(value = "userService1")//<bean id="userService" class=".."/>
        public class UserService1 {
          //Define dao type properties
          //No need to add set method
          //Add injection attribute annotation
          @Autowired
          private UserDao userDao;
        
          public void add() {
            System.out.println("service add.......");
            userDao.updata();
          }
        }
        
    2. @Qualifier: inject according to the name; This @qualifier annotation is used together with @Autowired above

      @Autowired  //Injection according to type
      @Qualifier(value = "userDaoimpl1")   //Inject by name
      private UserDao userDao;
      
    3. @Resource: can be injected according to type or name (not recommended):

      //@Resource / / inject according to the type
      @Resource(name = "userDaoImpl1") //Inject by name
      private UserDao userDao;
      
    4. @Value: inject common type attribute

      @Value(value = "abc")
      private String name;
      
    5. Full annotation development:

      1. Create a configuration class to replace the xml configuration file:

        @Configuration //As a configuration class, replace the xml configuration file
        @ComponentScan(basePackages = {"com.atguigu"})
        public class SpringConfig {
        }
        
      2. Write test classes:

        @Test
        public void testService2() {
         //Load configuration class
         ApplicationContext context
         = new AnnotationConfigApplicationContext(SpringConfig.class);
         UserService userService = context.getBean("userService", 
        UserService.class);
         System.out.println(userService);
         userService.add();
        }
        

Tags: Java Web Development Spring ioc xml

Posted by st0rmer on Fri, 05 Aug 2022 02:31:23 +0930