


A detailed introduction to the property configuration and custom property configuration of the Spring Boot series
In the process of using spring boot, you can find that only a very small amount of configuration is needed in the project to complete the corresponding functions. This is due to the modular configuration in spring boot. Each Starter that is relied on in pom.xml has Default configurations are sufficient for normal function development.
If you need to modify the custom or default configuration, spring boot provides a very simple method. You only need to add and modify the corresponding configuration in application.properties. (The default configuration of application.properties will be read when spring boot starts)
1. Modify the default configuration
Example 1. When spring boot develops web applications, the default startup port of tomcat is It is 8080. If you need to modify the default port, you need to add the following record in application.properties:
server.port=8888
Restart the project and you can see the startup log: Tomcat started on port(s): 8888 (http) Start port It is 8888, and you can access http://localhost:8888 normally in the browser.
Example 2, database connection information configuration in spring boot development (here using druid of com.alibaba), add the following records in application.properties:
druid.url=jdbc:mysql://192.168.0.20:3306/test druid.driver-class=com.mysql.jdbc.Driver druid.username=root druid.password=123456 druid.initial-size=1 druid.min-idle=1 druid.max-active=20 druid.test-on-borrow=true
The above two examples illustrate If you need to modify the default configuration in the starter module, you only need to add the configuration that needs to be modified in application.properties.
2. Custom property configuration
In addition to modifying the default configuration in application.properties, we can also configure custom properties here and load them in the entity bean.
1. Add custom property configuration in application.properties
com.sam.name=sam com.sam.age=11 com.sam.desc=magical sam
2. Write Bean class and load properties
Sam class needs to add @Component annotation so that spring can This class is scanned during startup and added to the spring container.
The first one: Use the @Value() supported by spring to load
package com.sam.demo.conf; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @author sam * @since 2017/7/15 */ @Component public class Sam { //获取application.properties的属性 @Value("${com.sam.name}") private String name; @Value("${com.sam.age}") private int age; @Value("${com.sam.desc}") private String desc; //getter & setter }
The second one: Use @ConfigurationProperties(prefix="") to set the prefix, and no annotations are needed on the properties.
package com.sam.demo.conf; import org.springframework.stereotype.Component; /** * @author sam * @since 2017/7/15 */ @Component @ConfigurationProperties(prefix = "com.sam") public class Sam { private String name; private int age; private String desc; //getter & setter }
3. Inject and use the Sam Bean in the controller.
package com.sam.demo.controller; import com.sam.demo.conf.Sam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author sam * @since 2017/7/14 */ @RestController public class IndexController { @Autowired private Sam sam; @RequestMapping("/index") public String index() { System.out.println(sam.getName() + " " + sam.getAge() + " " + sam.getDesc()); return "index"; } }
Browser access: http://localhost:8080/index, the console prints out the content of sam normally.
3. Detailed explanation of application.properties property configuration
1. Parameter reference and use of random number method
In application.properties, you can directly reference other objects through ${} The value of the attribute is as follows:
com.sam.name=sam com.sam.age=11 com.sam.desc=${name} is ${age} years old.
If you need to obtain a random number in application.properties, you can pass ${random}, as follows:
#获取随机字符串 com.sam.randomValue=${random.value} #获取随机字符串:${random.value} #获取随机int:${random.int} #获取10以内的随机数:${random.int(10)} #获取10-20的随机数:${random.int[10,20]} #获取随机long:${random.long} #获取随机uuid:${random.uuid}
2. Multi-environment configuration
In actual development, there may be different environments, including development environment, test environment, and production environment. Related configurations may be different for each environment, such as database information, port configuration, local path configuration, etc.
If you need to modify application.properties every time you switch to a different environment, the operation will be very cumbersome. Multi-environment configuration is provided in spring boot, making it easy for us to switch environments.
Create three new files in the same directory as application.properties:
application-dev.properties //开发环境的配置文件 application-test.properties //测试环境的配置文件 application-prod.properties //生产环境的配置文件
The above three files correspond to the configuration content of development, testing, and production respectively. The next step is how to selectively reference them. These are configured.
Add in application.properties:
spring.profiles.active=dev #引用测试的配置文件 #spring.profiles.active=test #引用生产的配置文件 #spring.profiles.active=prod
After adding spring.profiles.active=dev and starting the application, you will find that the configuration information of dev is referenced.
It can be seen that the above three configuration files conform to the application-{profile}.properties format, and the dev in spring.profiles.active=dev added in application.properties is exactly the profile in the above configuration file. Switching is instantaneous depending on the specific environment.
When using the command to run the jar package to start the application, you can specify the corresponding configuration.
java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
Attachment: Configuration method and priority
这些方式优先级如下: a. 命令行参数 b. 来自java:comp/env的JNDI属性 c. Java系统属性(System.getProperties()) d. 操作系统环境变量 e. RandomValuePropertySource配置的random.*属性值 f. jar外部的application-{profile}.properties或application.yml(带spring.profile)配置文件 g. jar内部的application-{profile}.properties或application.yml(带spring.profile)配置文件 h. jar外部的application.properties或application.yml(不带spring.profile)配置文件 i. jar内部的application.properties或application.yml(不带spring.profile)配置文件 j. @Configuration注解类上的@PropertySource k. 通过SpringApplication.setDefaultProperties指定的默认属性
Note: Command line Parameters, the way in which the jar package specifies parameters to start the application, may be unsafe. We can set it to prohibit starting the application in this way, as follows:
springApplication.setAddCommandLineProperties(false);
package com.sam.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { // SpringApplication.run(DemoApplication.class, args); SpringApplication springApplication = new SpringApplication(DemoApplication.class); //禁止命令行设置参数 springApplication.setAddCommandLineProperties(false); springApplication.run(args); } }
Additional:
In addition to supporting application.properties, the configuration in spring boot also supports the configuration method of application.yml, as follows:
Create a new application.yml instead of application.properties
server: port: 9999 com: sam: name: sam age: 11 desc: magical sam
Note: There are spaces in the middle of port: 9999. For yml syntax, please refer to: yml configuration file usage
The above is the detailed content of A detailed introduction to the property configuration and custom property configuration of the Spring Boot series. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: The working principle and configuration method of GDM in Linux systems In Linux operating systems, GDM (GNOMEDisplayManager) is a common display manager used to control graphical user interface (GUI) login and user session management. This article will introduce the working principle and configuration method of GDM, as well as provide specific code examples. 1. Working principle of GDM GDM is the display manager in the GNOME desktop environment. It is responsible for starting the X server and providing the login interface. The user enters

PyCharm is a powerful integrated development environment (IDE), and PyTorch is a popular open source framework in the field of deep learning. In the field of machine learning and deep learning, using PyCharm and PyTorch for development can greatly improve development efficiency and code quality. This article will introduce in detail how to install and configure PyTorch in PyCharm, and attach specific code examples to help readers better utilize the powerful functions of these two. Step 1: Install PyCharm and Python

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Understanding Linux Bashrc: Function, Configuration and Usage In Linux systems, Bashrc (BourneAgainShellruncommands) is a very important configuration file, which contains various commands and settings that are automatically run when the system starts. The Bashrc file is usually located in the user's home directory and is a hidden file. Its function is to customize the Bashshell environment for the user. 1. Bashrc function setting environment

How to configure a workgroup in Win11 A workgroup is a way to connect multiple computers in a local area network, which allows files, printers, and other resources to be shared between computers. In Win11 system, configuring a workgroup is very simple, just follow the steps below. Step 1: Open the "Settings" application. First, click the "Start" button of the Win11 system, and then select the "Settings" application in the pop-up menu. You can also use the shortcut "Win+I" to open "Settings". Step 2: Select "System" In the Settings app, you will see multiple options. Please click the "System" option to enter the system settings page. Step 3: Select "About" In the "System" settings page, you will see multiple sub-options. Please click

Title: How to configure and install FTPS in Linux system, specific code examples are required. In Linux system, FTPS is a secure file transfer protocol. Compared with FTP, FTPS encrypts the transmitted data through TLS/SSL protocol, which improves Security of data transmission. In this article, we will introduce how to configure and install FTPS in a Linux system and provide specific code examples. Step 1: Install vsftpd Open the terminal and enter the following command to install vsftpd: sudo

DRBD (DistributedReplicatedBlockDevice) is an open source solution for achieving data redundancy and high availability. Here is the tutorial to install and configure DRBD on CentOS7 system: Install DRBD: Open a terminal and log in to the CentOS7 system as administrator. Run the following command to install the DRBD package: sudoyuminstalldrbd Configure DRBD: Edit the DRBD configuration file (usually located in the /etc/drbd.d directory) to configure the settings for DRBD resources. For example, you can define the IP addresses, ports, and devices of the primary node and backup node. Make sure there is a network connection between the primary node and the backup node.

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.
