Spring framework learning notes 02 - streamlining spring configuration files with component annotations

Posted by bjoerndalen on Tue, 08 Mar 2022 01:33:29 +0100

I Course introduction

Last time, we used the XML configuration file and Spring container to manage Bean objects. Finally, we gave a question: "if we have dozens of classes to create beans and adopt XML configuration, will the Spring configuration file look very bloated? How to solve this problem?", In this talk, we are going to use component annotations to streamline Spring configuration files.

  • configuration: configuration
  • annotation

II Open the first lecture project

3, Using component annotations to streamline Spring configuration files

1. Create net tzj. spring. Lesson02 package

2. Copy the four classes of the lesson01 sub package to the lesson02 sub package

3. Modify dragon killing task class - SlayDragonQuest

  • Available annotations for business Bean configuration: @ Component - Component (@ Service - service, @ Repository)-
    Warehouse, @ Mapper - Mapper, @ Controller - Controller)

@component (instantiate the ordinary pojo into the spring container, which is equivalent to that in the configuration file)
Understand the annotation before exploring @ component? What is annotation? Annotation is essentially a class. In development, we can use annotation instead of xml configuration file

package net.tzj.spring.lesson02;

import org.springframework.stereotype.Component;

/**
 * Function: Dragon killing task
 * Author: Tang Zijie
 * Date: March 31, 2021
 */
@Component //Add a component annotation and leave it to the spring container for management. If no parameters are set, the default name of the component is slayDragonQuest
public class SlayDragonQuest {
    public void embark(){
        System.out.println("Execute the Dragon killing mission");
    }
}

Note: add the Component annotation @ component and leave it to the spring container for management. If no parameters are set, the default name of the component is slayDragonQuest

4. Modify the rescue mission class - rescue amselquest

package net.tzj.spring.lesson02;

import org.springframework.stereotype.Component;

/**
 * Function: Beauty rescue task
 * Author: Tang Zijie
 * Date: 4.7
 */
@Component
public class RescueDamselQuest {
    public void embark(){
        System.out.println("Carry out the task of saving the United States");
    }
}

5. Modify brave knight

  • Note: the setSlayDragonQuest() method is deleted because the Dragon killing task attribute of the brave knight has been set through the auto assembly annotation.
  • View source code annotation @ Component
package net.tzj.spring.lesson02;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Function: brave knight
 * Author: Tang Zijie
 * Date: March 31, 2021
 */
@Component("Mike") //Add the component unmarshaller and set the parameter "mike", which corresponds to the id value of the bean element in the spring configuration file
public class BraveKnight {
    @Autowired //Active assembly annotation (can be replaced by @ Resource or @ Inject annotation)
    private SlayDragonQuest slayDragonQuest;

//    public void setSlayDragonQuest(SlayDragonQuest slayDragonQuest){
//
//        this.slayDragonQuest = slayDragonQuest;
//    }

    public void embarkOnQuest(){
        slayDragonQuest.embark();

    }
}

@Component("mike") / / add the component unmarshaller and set the parameter "mike", which corresponds to the id value of the bean element in the spring configuration file (if you do not set the default is the class name, you can use mike to call)

@Autowired auto assembly program, so you don't need to write assembly. / / active assembly annotation (can be replaced by @ Resource or @ Inject annotation)

6. Modify the beauty saving Knight class - DamselRescuingKnight

package net.tzj.spring.lesson02;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Function: Beauty saving Knight
 * Author: Tang Zijie
 * Date: 4.7
 */

    @Component
public class DamselRescuingKnight {
        @Resource
    private RescueDamselQuest rescueDamselQuest;

//    public DamselRescuingKnight(RescueDamselQuest rescueDamselQuest){
//        this.rescueDamselQuest = rescueDamselQuest;
//    }

    public void embarkOnQuest(){
        rescueDamselQuest.embark();
    }
}

Note: the construction method is deleted because the beauty saving task attribute has been injected into the beauty saving Knight component through the resource annotation.
@The Resource has injected the beauty saving method, so the construction method is deleted

7. Create Spring configuration file

Create XML in the resources directory_ Annotation subdirectory, and then create the Spring configuration file - Spring config 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"
       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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--Component scanning: scan the classes or interfaces with annotations added under the specified package and generate them Bean object-->
    <context:component-scan base-package="net.tzj.spring.lesson02" />
</beans>

Component scanning: scan the classes (@ component, @ Service, @ Repository, @ Mapper, @ Controller) with annotations added under the specified package to generate Bean objects (as follows)

<context:component-scan base-package="net.tzj.spring.lesson02" />

8. Create test class - TestKnight

  • Create net in test/java tzj. spring. Lesson2 package, create TestKnight class in the package
package net.tzj.spring.lesson02;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
Function: Test Knight class
 Author: tzj
 Time: 4.12

 */
package net.tzj.spring.lesson02;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Function: Test Knight class
 * Author: tzj
 */
public class TestKnight {
    private ClassPathXmlApplicationContext context; // Application container based on classpath XML configuration file

    @Before
    public void init() {
        // Creating application container based on Spring configuration file
        context = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
    }

    @Test
    public void testKnight() {
        // Get the object from the application container by name
        BraveKnight knight1 = (BraveKnight) context.getBean("Mike");
        // Brave knight on mission
        knight1.embarkOnQuest();
        // Get the beauty Knight object from the application container according to the name
        DamselRescuingKnight knight2 = (DamselRescuingKnight) context.getBean("damselRescuingKnight");
        // The beauty saving Knight performs the mission
        knight2.embarkOnQuest();
    }

    @After
    public void destroy() {
        // Close the application container
        context.close();
    }
}

4, Program optimization - Interface oriented

  • The Spring framework can easily manage beans and their interdependencies. In order to realize loose coupling between modules, the interface oriented method is generally adopted. A variety of knights and missions can be matched at will. In order to achieve this effect, we should abstract out two interfaces: Knight interface and Quest interface. Knight interface has two implementation classes: BraveKnight and DamselRescuingKnight; The task interface has two implementation classes: SlayDragonQuest and rescue amselquest.

(1) Create task interface - Quest

package net.tzj.spring.lesson02;
/*
Function: task interface
 Author: tzj
 Date: 4.12
 */
public interface Quest {
    void embark();
}

(2) Create Knight interface - Knight

package net.tzj.spring.lesson02;
/*
Function: Knight interface
 Author: tzj
 Date: 4.12
 */
public interface Knight {
    void embarkOnQuest();
}

(3) Modify dragon killing task class - SlayDragonQuest

  • Let the Dragon killing task class implement the task interface

(4) Modify beauty rescue task class - rescue amselquest

  • Let the beauty rescue task class implement the task interface

(5) Modify brave knight class - BraveKnight

Note: the SlayDragonQuest class is changed to the Quest interface, so that the knight can be automatically assembled with any task (Bean that implements the Quest interface), which increases the flexibility of the program.

(6) Modify the beauty saving Knight class - DamselRescuingKnight

  • Let the beauty saving Knight class implement the knight interface

(7) Modify test class - TestKnight

(8) Then modify the test class - TestKnight

package net.tzj.spring.lesson02;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
Function: Test Knight class
 Author: tzj
 Time: 4.12

 */
public class Testknight {
    private ClassPathXmlApplicationContext context; //Application container based on path xml setting file

    @Before
    public void init(){
        //Creating application container based on Spring configuration file
        context  = new ClassPathXmlApplicationContext("xml_annotation/spring-config.xml");
    }
    @Test
    public void testBraveKnight(){
        //Get the object from the application container by name
        Knight knight = (BraveKnight) context.getBean("Mike"); //The parent interface variable points to the implementation class object
        // Brave knight on mission
        knight.embarkOnQuest();
    }
    @Test
    public void testDamselRescuingKnight(){
        //Get the beauty Knight object from the application container according to the name
        Knight knight = (DamselRescuingKnight) context.getBean("damselRescuingKnight"); //The parent interface variable points to the implementation class object
        //The beauty saving Knight performs the mission
        knight.embarkOnQuest();
    }


    @After
    public void destory(){
        //Close the application container
        context.close();

    }}


Operation results:

5, Classroom practice

  • Task 1. Two knights exchange tasks. Ask the brave knight to save beauty and the knight to kill the dragon.

  • Task 2. Both Knights perform two tasks. The brave knight is required to execute the Dragon killing task first, and then the beauty saving task. Ask the knight to save the United States to perform the task of saving the United States first, and then the task of killing the dragon.

  • Task 3. The two knights exchange tasks again. Ask the brave knight to complete the task of killing the dragon and the knight of saving the United States to complete the task of saving the United States.

Topics: Spring