Parsing Profile in Spring Boot: Dual control of configuration files and code

Create a spring boot project

There are many ways to create Web applications based on Spring Boot. We choose to create it directly in idea. Select the Spring Initializer website for the server URL , select the Maven project for the type, and select the java version according to the jdk version.
Insert image description here
Then add the corresponding dependencies and select the spring boot version

Insert image description here
Next we write a Controller

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    // 请求映射,用于处理请求
    @RequestMapping("/zcx")
    public Userinfo getUserInfo() {
    
    
        // 创建Userinfo对象
        Userinfo userinfo = new Userinfo();
        // 设置age属性
        userinfo.setAge("45");
        // 设置name属性
        userinfo.setName("zcx-yyds");
        // 返回Userinfo对象
        return userinfo;
    }

}

Now we need to package this application. Use the packaging tool on idea. Click package to package.
Insert image description here
We will get a springboot1-0.0.1-SNAPSHOT.jar file, and this jar file is an executable file that can be run directly. Built-in Tomcat web server. We directly use the following command to run this Spring boot program.

java -jar springboot1-0.0.1-SNAPSHOT.jar

Then we use postman to conduct project access testing and get the following return results, which proves that our program service has been started successfully.

Insert image description here
Now we understand how to build, package, and run a simple Web application.

Configuration system in spring boot

In Spring Boot, its core design concept is to use convention over configuration for the management of configuration information, which means that convention is greater than configuration .
Profile in Spring Boot is a very useful feature that allows us to control the behavior of the program through the configuration file without modifying the code.
In Spring Boot, Profile is a mechanism used to control application behavior. By using different Profiles, we can load different configuration information according to different environments or scenarios, thereby achieving flexible configuration of the application.

Configuration file and Profile

There are many sets of configurations depending on the environment. Suppose we have a collection of configuration files as shown below:
Insert image description here
the code in the configuration file application-dev.properties is:

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/dev_db
spring.datasource.username=root 
spring.datasource.password=666666

The code in the configuration file application-prod.properties is:

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/prod_db
spring.datasource.username=root 
spring.datasource.password=666666

Common configuration file naming methods are as follows:
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

In Spring Boot, we can use the following configuration in the main application.properties to activate the currently used Profile:

spring.profiles.active = dev

Of course, there are several ways to start Profile:

  1. Specify the Profile to activate in the main application.properties.
spring.profiles.active = dev
  1. Specify Profile in the startup command.
java -jar springboot1-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
  1. Display the settings Profile in the program. For example:
@SpringBootApplication
public class Springboot1Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication app = new SpringApplication(Springboot1Application.class);
        app.setAdditionalProfiles("dev");
        app.run(args);
    }
}

This will activate the Profile named prod.

Code Control and Profile

In Spring Boot, the application scenarios of the Profile concept also include dynamic control of the code execution process. To do this, we need to use the @Profile annotation. The Profile annotation can be used to specify that a certain class or method will take effect in a specific configuration environment. Annotations can be used as long as the class is annotated with @Componentor . Use an example to understand how to use Profile annotations:@Configuration@Profile

@Configuration
public class DataSourceConfig {
    
    
    @Bean
    @Profile("dev")
    public DataSource devDataSource() {
    
    

        //创建 dev 环境下的 DataSource
        return null;
    }

    @Bean()
    @Profile("prod")
    public DataSource prodDataSource() {
    
    

        //创建 prod 环境下的 DataSource
        return null;
    }

}

In this way, the same effect as using configuration files can be achieved.
Let's look at a more detailed example:

  1. Create an interface MyService:
public interface MyService {
    
    
    void doSomething();
}
  1. Create two different implementation classes, respectively for different configuration files.

@Component
@Profile("prod")
public class ProdMyService implements MyService {
    
    
    @Override
    public void doSomething() {
    
    
        System.out.println("Prod service is running.");
    }
}

@Component
@Profile("dev")
public class DevMyService implements MyService {
    
    
    @Override
    public void doSomething() {
    
    
        System.out.println("Dev service is running.");
    }
}

In the above example, we created two different implementation classes, one for developmentconfiguration files and another for productionconfiguration files. @ProfileThe annotation marks them separately so that Spring knows under which profile to activate them. 3. Specify the profile to activate in
the Spring profile (eg application.propertiesor ), for example: :application.ymlapplication.properties

spring.profiles.active=prod

Set spring.profiles.activeto development, which represents the development profile we wish to activate.
4. Create a startup class to demonstrate how to use MyService:

@SpringBootApplication
public class Springboot1Application implements CommandLineRunner {
    
    

    // 声明一个注入的MyService对象
    @Autowired
    private MyService myService;

    // 声明一个名为run的方法,用来启动Spring应用
    public static void main(String[] args) {
    
    
        // 调用SpringApplication的run方法,传入Springboot1Application类和args参数
        SpringApplication.run(Springboot1Application.class, args);
    }

    // 方法run,用来执行Spring应用的业务逻辑
    @Override
    public void run(String... args) {
    
    
        // 调用myService的doSomething方法
        myService.doSomething();
    }
}

Insert image description here
Through the results, we found that when running this application, it will spring.profiles.activeselect the corresponding implementation class according to the properties in the configuration file.
If you want to know more, please refer to the spring boot official website .

Guess you like

Origin blog.csdn.net/st200112266/article/details/132791559