SpringBoot core configuration and annotations

Table of contents

1. Notes

meta annotation

Basic annotation

start comment

Two, configuration

format introduction

Read configuration file information

Case Demo 1

 Nested read bean information

Case Demo 2

 Read Map, List and Array type configuration data

Case Demo 3

 3. Summary


1. Notes

        Before we learned about the basics of SpringBoot and the simple application of AOP, this issue will talk about the core configuration and annotations of SpringBoot 

        SpringBoot annotations are the ability to label code. By introducing annotations, we can simply and quickly give life to the code, greatly improving the readability and scalability of the code. Annotation itself does not have any capabilities, it is just a label, but we can define various labels and implement various label processors to extend functions, enable functions, define attributes, define behaviors, and define rules for classes, methods, attributes, and even parameters. , association processing, metadata definitions, and more.

meta annotation

@Documented : The annotation will be listed in the javadoc document of the element annotated by this annotation. Generally, there is no harm in marking this annotation

@Target

        The target elements to which annotations can be applied, such as classes, methods, attributes, parameters, etc., need to be carefully considered

@Retention

        Only retain the source code, keep it until the compiled bytecode, or load it at runtime, more than 90% of the applications will parse annotations for additional processing at runtime, so in most cases we will set the configuration to RetentionPolicy .RUNTIME

@Inherited

        If the subclass does not define annotations, it can automatically obtain annotations that define inheritance attributes from the parent class. For example, Spring's @Service has no inheritance characteristics, but @Transactional has inheritance characteristics. Spring annotations are used in the OO inheritance system Please pay special attention to this point. It is taken for granted that annotations can be inherited by subclasses, which may cause unnecessary bugs. You need to carefully consider whether to enable inheritance

@Repeatable

        The feature introduced by Java 8 defines repeatable annotations through associated annotation containers. A little syntactic sugar improves code readability. It is actually very common to have multiple repeated annotations for elements. For example, a method can be accessed by a role or It can be accessed by the B role. A certain method needs to be executed as a scheduled task, and it needs to be executed under the A condition as well as under the B condition.

@Native

        Whether to generate marked fields in the .h header file, unless native programs need to interact with Java programs, this meta-annotation is rarely used

Basic annotation

@Service : Annotated on the class, indicating that this is a business layer bean

@Controller : Annotated on the class, indicating that this is a control layer bean

@Repository : Annotated on the class, indicating that this is a data access layer bean

@Component : The annotation is on the class, indicating the general bean, if the value is not written, the default is the first letter of the class name is lowercase

@Autowired : Inject by type. Default attribute required=tru

@Resource: Assembled by name.

start comment

 SpringBootApplication

Include the following three annotations:

 @SpringBootConfiguration

          @Configuration: The function of JavaConfig, the configuration class, combined with @Bean can inject objects into the spring IOC container. The class annotated with @SpringBootConfiguration is a configuration class.

@EnableAutoConfiguration

         Turn on automatic configuration. Create the objects in spring and third-party libraries, inject them into the spring container to avoid writing xml, and remove the sample code. Objects to be used, provided by the framework.

 @ComponentScan 

         Component scanner, <context:component-scan base-package="xxx package"/> scans @Controller, @Service, @Repository, @Component annotations, creates their objects and injects them into the container

The springboot convention: the startup class, as the root (starting point) of the scanning package


Two, configuration

format introduction

Configuration files have two formats : properties and   yaml ( yml ).

        properties is a commonly used configuration file format in Java, and the file extension is properties.

The syntax format is: key=value. keys are unique.

        yaml (Yet Another Markup Language), is a data format for configuration files, and the file extension is yaml or yml (commonly used)

The syntax format is: key:[space] value.


Basic syntax rules of YAML:

 Case sensitive

 Use indentation to represent hierarchical relationships

 Only spaces can be used for indentation, tab keys are not allowed

 The number of spaces for indentation is not important, as long as elements at the same level are left-aligned

 The # character represents a comment, and only supports single-line comments. # put the first character of the comment line

YAML indentation must use spaces and is case-sensitive. It is recommended to use only lowercase and spaces when writing YAML files.

YAML supports three data structures

 Object: a collection of key-value pairs, also known as mapping (mapping) / hash (hashes) / dictionary (dictionary)

 Array: a set of values ​​arranged in order, also known as sequence (sequence) / list (list)

 Scalars: single, indivisible values, such as numbers, strings, true|false, etc.

Storage path: src/main/resource directory or /config of the class path

Read configuration file information

        Spring Boot supports configuration files in both  properties and yml   formats. The configuration file name is  application  by default . We can use application.properties  ,  application.yml .

Read the key value of the configuration file, and inject the property of the Bean with @Value, and @Value injects the value of a key at a time.

Binding multiple key values ​​to Bean multiple properties can cooperate with ConfigurationProperties annotation. 

Accessing properties in code can also use the abstract object Environment for externalized configuration. Use Environment to inject this object and call its getProperty(String key) method.

Case Demo 1

        Requirements : Provide the application's name, owner, and port basic information in application.properties, and the program will read these data and display them to the user.

        Step 1: Create a new maven project without adding dependencies

        Step 2: Customize configuration items in application.properties

        Step 3: Create SomeService class to read app.name, app.owner, app.port configuration keys.       

        Annotation @Value reads a single value, syntax ${key: default value}

     

@Service
public class SomeService {
    @Value("${app.name}")
    private String name;

    @Value("${app.owner}")
    private String owner;

    @Value("${app.port:8088}")
    private Integer prot;

    public void printValue(){
        //链接字符串
        StringJoiner joiner = new StringJoiner(";");
        joiner.add(name).add(owner).add(String.valueOf(prot));

        //打印出字符串
        String result = joiner.toString();
        System.out.println("result= "+ result);
    }

         Step 4: Unit Testing

        Create a test class in the test directory, inject the SomeService object, and call its printValue() method.


 Nested read bean information

Case Demo 2

        Requirements: The Bean contains other Beans as attributes, and the configuration items in the configuration file are bound to the Bean and members of the reference type. Bean definition has no special requirements.

        Step 1: Create a new file with a .yml suffix under the resources folder and add dependencies

       Add the following dependencies to the pom.xml file  

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Step 2: Create a new pk02 package and create two classes

//DoubBean 
@Configuration(proxyBeanMethods = false)
@ConfigurationProperties(prefix = "app1")
@Service
public class DoubBean {
    private String name;
    private String owner;

    private Integer port;
    private Seri ser;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }


    public Seri getSer() {
        return ser;
    }

    public void setSer(Seri ser) {
        this.ser = ser;
    }

    @Override
    public String toString(){
        return "DoubBean{ \n"+
                "网站名="+name+"\n" +
                ",浏览器cookic="+owner+"\n" +
                ",端口="+port+"\n" +
                "用户信息:"+ser+
                "}";
    }
// Seri 
public class Seri {
    private String username;
    private String userpass;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpass() {
        return userpass;
    }

    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }

    @Override
    public String toString(){
        return "用户名:" + username +"  用户密码:" + userpass;
    }
    
}

         Step 3: Add scan package and unit test method

Be sure to add scanning annotations to the startup class first , and set up the scanned package


 Read Map, List and Array type configuration data

Case Demo 3

Map, List and Array can all provide configuration data, the following demonstrates the process through an example configuration:

        Step 1: Write different types of data in the application.yml file just now

        Step 2: Add the pk3 package and create the following class files

//Users 
public class Users {
    private String name;
    private String sex;
    private Integer age;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString(){
        return "MyServer{ " +
                "name: " + name +"\n"+
                "sex: " + sex +"\n" +
                "age= "+age+"  }"+"\n";


    }
}
//ConutClass 
@Data
@ConfigurationProperties
public class ConutClass {
    private List<Servers> servers;
    private Map<String,Users> users;

    private String [] names;

    @Override
    public String toString(){
        return "ConutClass{ \n"+
                "网站服务器:"+"\n"+servers+"\n" +
                "用户信息列表:"+"\n"+users+"\n" +
                "名字列:"+"\n"+names+"\n" +
                "}";
    }
}
//Servers 
public class Servers {
    private String title;
    private String ip;
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    @Override
    public String toString(){
        return "MyServer{ " +
                "title: " + title +"\n"+
                "ip: " + ip + "  }"+"\n";
        
    }
}

        Step 4: Add scan package and test unit

The @ConfigurationPropertiesScan annotation can only be added once, so multiple scan packages can be stored in braces and separated by commas

 3. Summary

In this article, we focus on common annotations and reading and testing of beans.

        Spring Boot uses  application.properties or  application.yml files to manage the configuration of the application

   @SpringBootApplicationThe annotation is used to start the startup class of the Spring Boot application, which combines the functions of @Configuration, @EnableAutoConfigurationand @ComponentScan. @RestControllerAnnotations mark a class as a controller for a RESTful API, and @RequestMappingannotations are used to map HTTP requests to controller methods.

        In addition, annotations for dependency injection @Autowired, which can automatically inject dependencies. The last is @Beanthe annotation, which can register the instance returned by the method as a bean and add it to Spring's application context.

This is the end of the content of this article. If you have good suggestions and inadequacies, you are welcome to like and forward in the comment area.

Guess you like

Origin blog.csdn.net/qq_51294997/article/details/132112903