StarYuhen

StarYuhen

Getting Started with Spring Boot

Preface#

I wrote this to record my introductory article on learning the SpringBoot framework, without looking at the source code or anything like that, which I will look at later.

It took a total of 9 hours to learn the SpringBoot framework.

I learned the basics of usage and the configuration and usage of Redis and MySQL.

And also recorded the pitfalls encountered.


Parameters, Comments, and Pitfalls#

Entry Parameters#

@SpringBootApplication(scanBasePackages = "com.example")
// Reference mybatis plus and scan the mapper package at the same time
@MapperScan("com.example.springbootlearn.mapper")

I usually put these two comments at the entry point.

The scan package in SpringBootApplication can automatically scan the components and others inside.

MapperScan is used to scan the mapper, so there is no need to use the @Mapper annotation for inherited functions.


About URL Requests#

@RestController

This is the routing control layer, which is a simplified way of combining @Controller and @ResponseBody.

    @GetMapping("/get/{id}/test/{name}")
    public Map<String, Object> GetPathController(
            @PathVariable("id") Integer id,
            @PathVariable Map<String, String> PathMap,
            @RequestHeader("User-Agent") String Agent,
            @RequestHeader Map<String, String> HeaderMap,
            @RequestParam("age") Integer age,
            @RequestParam Map<String, String> ParamMap,
            @CookieValue("test") String test
    ) {
    @PathVariable gets the value corresponding to the request path
        It can also use Map to receive all the values passed, such as Map<String,String>
    @RequestHeader gets the header parameters of the request, User-Agent means getting the browser identifier of the request
        It can also use Map to receive all the values passed, such as Map<String,String>
    @RequestParam gets the Param value of the request, such as the Get request /get/test?age=10&name="Test"
    @CookieValue gets the Cookie value of the request
    @RequestAttribute gets the domain attribute
    @RequestBody gets the Json value of the post request and automatically serializes it

GetMapping is a simplified way of writing URL requests, and PostMapping is the way to write Post requests.

    @RequestMapping(value = "Name", method = RequestMethod.POST)

About URL Responses#

    @ResponseBody // Response body

This annotation needs to be added to the method if we want to respond in XML and JSON format, and we need to import two plugin libraries.

    // Reference JSON response library
    implementation 'org.springframework.boot:spring-boot-starter-json'
    // Reference XML response library
    implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'

SpringBoot will automatically determine whether to return XML or JSON data based on the accept request, and this requires enabling the configuration.

# accept
spring.mvc.contentnegotiation.favor-parameter=true

Custom Components#

@Component

Using this annotation is enough, and you can also customize it by adding specific classes to it.

@Import({AsyncAppender.class})

  @Bean("PetConfig")

This annotation declares the specified ID of the container component, which is equivalent to a name.

There is also a filtering parameter:

// Set when there is this component in the container, this configuration class code will take effect, perform component injection, and if there is no specified component, all the code below the comment will not be used
// For example: if this configuration class does not have the PetConfig component, then MyConfig will not be used at all. If this annotation is added in front of the method, if the condition is not met, the method will not be used
@ConditionalOnBean(name = "PetConfig")

When we need to determine whether a component is used or see which components are used, we can check at the entry point of SpringBoot:

//        ConfigurableApplicationContext run = SpringApplication.run(SpringBootLearnApplication.class, args);
        // View the components used by the framework
//        String[] GetSpringBootName = run.getBeanDefinitionNames();
//        for (String Name : GetSpringBootName) {
//            System.out.println(Name);
//        }
//        // Get the specified component
//        Pet pet = run.getBean("PetConfig", Pet.class);
//        System.out.println(pet);
        // Check if the specified component exists in the container
//        boolean Pet = run.containsBean("PetConfig");
//        System.out.println(Pet);

How to Customize Reading Configuration YAML#

// Get the configuration file information, because it is in the form of a prefix, so this function is needed
@PropertySource(value = "classpath:application.yaml")
@ConfigurationProperties(prefix = "database")
// Use annotations to inject setter and getter methods, although they can be automatically generated, lombok methods can still be used
@Data

This annotation in YAML is represented as:

91bf9aae-6385-4542-95ef-9c1045cf3e26.png

@Data is a method in the lombok library, which mainly provides setter and getter methods for private variables, automatically generated.

    // Lombok simple development library, use annotationProcessor to import
    annotationProcessor 'org.projectlombok:lombok'
    // Also import the package during build
    compileOnly 'org.projectlombok:lombok'

How to Use Mybatis Plus#

  1. Define a class that contains the parameters of the data table

    @Data
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    
  2. Use an interface to inherit from the Mybatis Plus class

    @Component
    public interface UserMapper extends BaseMapper<User> {
    
    }
    
    

Configuration of the libraries that need to be used:

implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
    // Use Alibaba's database management pool, there is also a kpl project that needs to specify the version
    // implementation 'com.alibaba:druid:1.2.15' Use the official version of the Spring framework
    implementation 'com.alibaba:druid-spring-boot-starter:1.2.15'
    // Reference Java MySQL driver
    implementation 'mysql:mysql-connector-java'
    // Reference Mybatis
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.1'
    // Reference Mybatis plus https://baomidou.com/pages/24112f/#%E6%94%AF%E6%8C%81%E6%95%B0%E6%8D%AE%E5%BA%93
    implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.3.1'

The reason for showing the configuration is that in some cases, the wrong package may be found, so here is a corresponding explanation.

To use the SpringBoot and Mybatis plus test packages, the configuration needs to be written as follows:

    // Reference SpringBoot test library
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    // Reference Mybatis plus test library
    testImplementation 'com.baomidou:mybatis-plus-boot-starter-test:3.5.3.1'

Mybatis plus documentation


Code files are in the Github project.

That's about it for getting started, and I'll go look at the source code.


Test Annotations#

/*
Test common annotations
● @Test: Indicates that the method is a test method. However, unlike @Test in JUnit4, its responsibility is very single and cannot declare any attributes. Additional tests will be provided by Jupiter
● @ParameterizedTest: Indicates that the method is a parameterized test, which will be explained in detail below
● @RepeatedTest: Indicates that the method can be executed repeatedly, which will be explained in detail below
● @DisplayName: Sets the display name for the test class or test method
● @BeforeEach: Indicates that it will be executed before each unit test
● @AfterEach: Indicates that it will be executed after each unit test
● @BeforeAll: Indicates that it will be executed before all unit tests
● @AfterAll: Indicates that it will be executed after all unit tests
● @Tag: Indicates the category of unit tests, similar to @Categories in JUnit4
● @Disabled: Indicates that the test class or test method will not be executed, similar to @Ignore in JUnit4
● @Timeout: Indicates that if the test method runs for more than the specified time, an error will be returned
● @ExtendWith: Provides an extension class reference for the test class or test method
 */
// Assertions can be used for assertion
/*
Inject parameters into the test
@ValueSource: Specifies the source of input parameters for parameterized tests, supporting the eight basic types as well as String types and Class types
@NullSource: Indicates that a null input parameter is provided for parameterized tests
@EnumSource: Indicates that an enumeration input parameter is provided for parameterized tests
@CsvFileSource: Indicates that the specified CSV file content is read as input parameters for parameterized tests
@MethodSource: Indicates that the return value of the specified method is read as input parameters for parameterized tests (note that the method return needs to be a stream)
 */
// Use tests
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.