SpringBoot Introduction Tutorial 03-Detailed Explanation of SpringBoot Configuration File

SpringBoot Introduction Tutorial 03-Detailed Explanation of SpringBoot Configuration File

Although springboot has automatically done a lot of configuration for us, so that the application can run without any configuration, but in actual application scenarios, we still need to modify some configurations by ourselves. This article mainly describes how to customize the configuration and how to read the customized configuration in the application.

Custom configuration

When we create a springboot application, the system defaults to us creating an application.properties file in the src/main/java/resources directory. Springboot supports configuration files in two formats, properties and yml, but the yml file is much more powerful than properties, so here it is uniformly changed to application.yml.

Then add the following content in application.yml:

server:
  port: 8888

Then add the following content to the HelloController class:

@Value("${server.port}")
private int port;

@Value("${server.port1:9999}")
private int port1;

@RequestMapping("/port")
public String port(){
    
    
    return "server.port is " + port;
}

@RequestMapping("/port1")
public String port1(){
    
    
    return "server.port1 is " + port1;
}

Then run the main method of SpringbootDemoApplication to start the application

Open the browser and enter http://127.0.0.1:8888/port, the system returns server.port is 8888

Open the browser and enter http://127.0.0.1:8888/port1, the system returns server.port1 is 9999

As can be seen from the above example, @Value("${placeHolder}") can be used to inject properties. If a non-existent placeholder is injected, an error will be reported when the system starts, which can be solved by @Value("${placeHolder:defaultValue}")

Developer tools

If you want to be good at your work, you must first sharpen your tools. Before the next section, I will add a few developer tools, that is, the 3 developer tools checked in the first section when using Spring Assistant to build a project

  • Spring Boot DevTools applies hot start tools, which can be automatically loaded when the code changes without restarting, developing and debugging artifacts
  • Lombok is an efficiency artifact. You only need to add @Data annotations to the javabean class. Getter, setter, toString, hashcode, equals and other methods can be automatically generated, and it is generated in the class file. The java code looks very refreshing. Need to install the lombok plug-in (free) in idea.
  • Spring Configuration Processor prompts when writing application.properties file and application.yml file, such as entering spring.datasource when configuring database, there will be a list of keys to choose from, which is very convenient

If it is not checked when creating a new project, it can also be added through the pom file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Custom profile

Create a new user.properties file in the src/main/java/resources directory with the following content:

user.name=henry
user.age=26

Then create a new config package under the com.henry package, and then create a new UserBean class under the config package, the code is as follows:

@Configuration
@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix = "user")
@Data
public class UserBean {
    
    
    private String name;
    private int age;
}
//一个@Data注解搞定,省去getter/setter/toString等方法,是不是很清爽

Then create a new UserBeanController class under the com.henry.controller package, the code is as follows:

@RestController
public class UserBeanController {
    
    
    @Autowired
    private UserBean userBean;

    @RequestMapping("/user")
    public String user(){
    
    
        return userBean.getName() +"-"+ userBean.getAge();
    }
}

Then we start the application, open the browser and enter http://127.0.0.1:8888/user, the browser displays:

Henry-26

Let's first look at a few annotations on UserBean

@Configuration is equivalent to @Component, @Service, which declares that the javabean is managed by the spring container

@Data code simplified annotation

@PropertySource specifies which configuration file to read properties from

  • @PropertySource("classpath:user.properties") read from user.properties under classpath
  • @PropertySource(value = {"classpath:user.properties"}) supports reading from multiple configuration files, {"xxx","xxx2",...}
  • @propertySource has a property ignoreResourceNotFound, the default value is false, if the configuration file does not exist, an error will be reported, and if it is changed to true, it will be ignored

@ConfigurationProperties specifies the prefix prefix = "user", and there are two additional properties. The default value of ignoreUnknownFields is true, and fields that cannot be found are ignored; the default value of ignoreInvalidFields is false, and an error will be reported for illegal fields. For example, the age field in the java class is Int type, but the age value of the configuration file is abc, an error will be reported

The SpringBoot application reads the configuration file at startup, generates the javabean configuration class, and assigns values ​​to the fields, and then puts them in the spring container for management, and then can be used normally in other parts of the application. For example, in the above example, the UserBeanController is injected through the @Autowired annotation. be usable

application.yml configures multiple environments

In the actual development process, we often encounter the need to cut through multiple environments. Let’s talk about how to configure application.yml at this time.

Code directly

spring:
  profiles.active: dev

---
spring:
  profiles: dev
server:
  port: 8080

---
spring:
  profiles: stg
server:
  port: 8888

---
spring:
  profiles: prod
server:
  port: 9999

As above, we have defined 3 environments, namely dev, stg, prod, and designated the current environment as dev

Start the application directly, you can see tomcat started on port(s): 8080 (http) with context path in the startup log''

If we want to switch to the stg environment, there are several ways

  1. **Change the profiles.active in application.yml to stg**
  2. **Specify application parameters--spring.profiles.active=stg **
  3. **Specify the vm parameter -Dspring.profiles.active=stg **

Enter the edit configurations interface through the ALT+SHIFT+F10 shortcut key
Insert picture description here

After the 2 steps shown in Figure, run the main method of SpringbootDemoApplication to read the configuration of stg.

Package deployment, start script to specify environment

maven clean first, then install

After the packaging is complete, open the Terminal tool of idea and enter the command

cd target
java -jar springboot-demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=stg

Here is a point, the way to specify application parameters can override the configuration in application.yml

That is to say, the method of applying parameters (--spring.profiles.active=stg) has priority over the configuration file method

The configuration file method is higher than the jvm parameter method (-Dspring.profiles.active=stg), you can try it yourself

After the test, switch the environment back to dev, and subsequent tutorials will develop and run in the dev environment by default.

Guess you like

Origin blog.csdn.net/l229568441/article/details/106935711