Profile in Spring Boot: Principles, usage and examples

Profile in Spring Boot: Principles, usage and examples

foreword

Spring Boot is a framework for rapid development of Spring applications, which provides many useful functions and features. Among them, Profile is a commonly used function, which can load different configuration files according to different environment configurations, so as to realize different configuration logics. This article will introduce the principle, usage and examples of Profile in Spring Boot.

insert image description here

The principle of Profile

In Spring Boot, Profile is implemented through configuration files. In different environments, different configuration files can be loaded to implement different configuration logic. Specifically, Spring Boot supports the following configuration files:

  • application.properties
  • application.yml
  • application-{profile}.properties
  • application-{profile}.yml

Among them, application.properties and application.yml are common configuration files, which will be loaded in all environments. And application-{profile}.properties and application-{profile}.yml are configuration files loaded according to different Profiles. When the application starts, Spring Boot decides which configuration file to load based on the current environment variables. For example, if the current environment variable is dev, the application-dev.properties or application-dev.yml file will be loaded.

Profile usage

In actual development, Profile can be used to achieve the following functions:

  • Differentiate between different environments, such as development, test, and production.
  • Configure different database connection information, for example, the development environment uses a local MySQL database, the test environment uses a remote MySQL database, and the production environment uses an Alibaba Cloud RDS database.
  • Configure different log levels, for example, the development environment uses DEBUG level, the test environment uses INFO level, and the production environment uses WARN level.

The steps to use Profile are as follows:

1. Create a configuration file

First, you need to create different configuration files under the resources directory of the project, for example:

  • application-dev.properties: The configuration file for the development environment.
  • application-test.properties: configuration file for the test environment.
  • application-prod.properties: The configuration file for the production environment.
# application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
logging.level.root=debug
# application-test.properties
spring.datasource.url=jdbc:mysql://remote-server:3306/test
spring.datasource.username=test
spring.datasource.password=test123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
logging.level.root=info
# application-prod.properties
spring.datasource.url=jdbc:mysql://aliyun-rds:3306/test
spring.datasource.username=prod
spring.datasource.password=prod123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
logging.level.root=warn

2. Configure Profile

In the configuration file of the project, the current Profile needs to be configured. There are two methods:

  • Configured in the application.properties file.
spring.profiles.active=dev
  • Configured in the start command.
java -jar myproject.jar --spring.profiles.active=dev

3. Use configuration

In the code, configuration information can be injected through the @Value annotation. For example:

@Service
public class UserService {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    // ...
}

Profile example

Below is an example project using Profile.

1. Create a project

First, create a new Spring Boot project using Spring Initializr, adding the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database

2. Create a configuration file

Create the following configuration file under the resources directory of the project:

  • application-dev.properties
spring.datasource.url=jdbc:h2:mem:devdb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
logging.level.root=debug

-application-test.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
logging.level.root=info
  • application-prod.properties
spring.datasource.url=jdbc:h2:mem:proddb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
logging.level.root=warn

3. Configure Profile

Configure the current Profile in the application.properties file:

spring.profiles.active=dev

4. Create entity class and DAO

Create a User entity class and a UserRepository interface for operating the database.

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    // getters and setters
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

5. Write the controller

Create a UserController controller to handle HTTP requests.

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
}

6. Run the project

Start the project with:

java -jar myproject.jar --spring.profiles.active=dev

Then, you can use Postman or curl tools to test the project. For example, send the following POST request:

POST http://localhost:8080/users
Content-Type: application/json

{
    "username": "alice",
    "password": "123456"
}

As you can see, the request is successful and the created User object is returned.

7. Test different profiles

Try to modify the spring.profiles.active property in application.properties and restart the project to test different Profiles. For example, modify it to test:

spring.profiles.active=test

Then, run the project again, and send a POST request:

POST http://localhost:8080/users
Content-Type: application/json

{
    "username": "bob",
    "password": "123456"
}

It can be seen that the request is successful and the created User object is returned, but the log level output on the console has changed to the INFO level.

in conclusion

Profile is a very useful feature in Spring Boot, which can help us achieve different configurations in different environments. This article introduces the principle, usage and examples of Profile, hoping to help readers better understand and use the Profile function in Spring Boot.

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/131455033