Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of Spring Boot configuration

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what are the Spring Boot configuration methods?". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Overview

The current Spring Boot version: 2.3.4.RELEASE, this update speed is also swishing, with the release of the new version, but also step by step for the company's basic components to upgrade, of which a very important part is the update of the configuration file (although Apollo is now fully used). I also combed through the configuration file for the new version of Spring Boot and did find something I hadn't noticed before.

Second, the new version of the external configuration 1. Basic configuration loading

Spring Boot provides us with a lot of external configuration parameters, and we can use YAML files (of course you can also use properties, but not recommended), environment variables, and command-line parameters to distinguish between different environment configurations.

There are two ways to use a configuration:

Use the annotation @ Value to inject the attributes contained in the Environment

Use @ ConfigurationProperties to define a property class that contains the properties we need (all of which can be configured in YAML)

There are so many external configurations for Spring Boot, which one will take effect if all of them are configured?

Spring Boot loads the configuration in the following order, from high priority to low priority (the same configuration with high priority will override the low one), and from outside to inside to load the configuration overlay:

1) the properties file of the developer's global configuration (spring-boot-devtools.properties under $HOME/.config/spring-boot when the developer tool is activated)

2) the @ TestPropertySource ("base.properties") annotation is configured to load the configuration in the test, such as base.properties

3) properties of @ SpringBootTest is used in the test

4) Command line parameter configuration, that is, the configuration used later in java-jar

5) SON configurations that can be loaded using the SPRING_APPLICATION_JSON attribute can be loaded in two ways:

Load SPRING_APPLICATION_JSON=' {"persion": {"name": "xxx"}'in the system environment variable, which adds this data to Spring Environment. We can get a property of persion.name with a value of xxx.

Use the System attribute to load java-Dspring.application.json=' {"persion": {"name": "xxx"}'- jar app.jar, which loads the value of the spring.application.json property as a String and is not parsed.

6) configuration initialized by ServletConfig

7) configuration initialized by ServletContext

8) JNDI characteristics of java:comp/env

9) the system properties of Java, which are obtained by System.getProperties ()

10) Environment variables configured by the operating system

11) configure in RandomValuePropertySource with random. Attributes at the beginning

12) if you apply the externally configured application- {profile} .properties or YAML, you can use spring.profiles.active to select the configured environment. If you do not choose the default, it is application-default.properties. We can use spring.config.location to define the path of the file to load.

13) application- {profile} .properties or YAML configured inside your application is also used for multiple environment loading options. You can use spring.profiles.active to activate the configuration.

14) apply externally configured application.properties or YAML

15) apply internally configured application- {profile} .properties or YAML.

Here the SpringApplication of 14 and 15 will load the configuration properties from application.properties.

This configuration overrides the loading from four locations from high priority to low priority, and the high priority overrides the low priority. Let's take a look:

Apply application.properties or application.yml under the / config folder in the external current directory

Apply application.properties or application.yml in the current directory externally

Apply / config under the internal classpath, that is, application.properties or application.yml under the resources/config directory

Application.properties or application.yml under the internal classpath of the application, that is, under the resources directory

16) the @ PropertySource annotation is configured on the @ Configuration configuration class, but this configuration will not be loaded into the Environment until the spring context is refreshed. This loading method does not configure properties that need to be loaded before the application context is refreshed, such as logging.* and spring.main.*.

Mode of use:

/ / load the classpath:/com/myco/app.properties file @ Configuration @ PropertySource ("classpath:/com/myco/app.properties") public class AppConfig {@ Autowired Environment env; @ Bean public TestBean testBean () {TestBean testBean = new TestBean (); testBean.setName (env.getProperty ("testbean.name")); return testBean;}}

17) parameters set by SpringApplication.setDefaultProperties

Let's use a Demo to say:

Import org.springframework.stereotype.*;import org.springframework.beans.factory.annotation.*;@Componentpublic class MyBean {@ Value ("${name}") private String name; / /...}

You can use application.yml under classpath to configure name= laowang

You can use an external application.yml to set a name = laoli to override the previous configuration (laoli if the current name gets)

You can use java-jar app.jar-- name= "Spring" to override the previous configuration (Spring if the current name is obtained)

Spring Boot configuration files also support wildcard loading, for example, when using spring.config.additional-location and spring.config.location to load configurations, you can use wildcards to load multiple files.

2. Configure random attributes

The injection of random attributes is actually achieved through RandomValuePropertySource, which can help us generate random values of integers, longs, uuid, and strings. This is very practical for us to conduct some test cases at ordinary times.

/ / can be configured in application.ymlmy.secret=$ {random.value} my.number=$ {random.int} my.bignumber=$ {random.long} my.uuid=$ {random.uuid} my.number.less.than.ten=$ {random.int (10)} my.number.in.range=$ {random.int [1024je 65536]} 3, command line attributes

We can use java-jar-- server.port=9000 to add the command line parameter server.port to the Environment of our application, which can be obtained using @ Value and other methods. Under normal circumstances, the attribute priority added by the command line is our high priority.

If you don't want to add command-line attributes to the application's Environment, you can configure SpringApplication.setAddCommandLineProperties (false).

In fact, the most frequently used command line load is probably the javaagent attribute, which is essential for today's companies, APM monitoring. We can also use it for testing by temporarily loading some properties through the configuration of the command parameters.

4. Apply load configuration file

In fact, it has already been mentioned above, and it will be mentioned again here. SpringApplication loads property configurations from application.yml and adds them to Spring's Environment for us to use. The priority is as follows, and the high priority covers the low one (put an original version here, you can try to understand it yourself):

A / config subdirectory of the current directory

The current directory

A classpath / config package

The classpath root

If you don't like the configuration file called application.properties, you can also use spring.config.name to configure it. You can also use spring.config.location to specify the configuration load path.

Examples are as follows:

/ / modify my configuration file called myprojectjava-jar myproject.jar-- spring.config.name=myproject / / load my configuration file java-jar myproject.jar-- spring.config.location=classpath:/default.properties,classpath:/override.properties somewhere else

Because the spring.config.name and spring.config.location configurations are used to determine which properties the application needs to load, it needs to be loaded as early as possible. It is generally used by means of system environment variables, system parameters, and command line loading.

The default configuration loading path is as follows, and the installation priority is sorted from high to low (file:./config/ has the highest priority), so be sure to pay attention to it when using loading:

File:./config/

File:./config/*/

File:./

Classpath:/config/

Classpath:/

5. The use of placeholders

In application.properties, we can use placeholders to dynamically load attributes.

For example, we can use profile of maven to dynamically replace the environment parameters (such as replacing mysql, redis and other domain names) when packaging.

The last few examples are:

/ / simply use app.name=MyAppapp.description=$ {app.name} is a Spring Boot application / / with the command line parameter, such as adding-- port=9000 instead of-- server.port=9000, then we can configure server.port=$ {port:8080} in the configuration file.

One thing to note:

If you integrate spring-boot-starter-parent into your POM, the default maven-resources-plugins plug-in will use @ maven.token@ instead of ${maven.token}. This is actually done to prevent conflicts with Spring placeholders, so if we use maven's profile or something else to dynamically replace application.properties internal properties, please use @ name@.

6. YAML file for multi-environment configuration

1) profile u

In application.yml, you can use spring.profiles to activate the environment configuration content you want to load.

Example:

Server: address: 192.168.1.100---spring: profiles: developmentserver: address: 127.0.0.1---spring: profiles: production & eu-centralserver: address: 192.168.1.120

In the above example, if we activate development, then server.address is 127.0.0.1. If production & eu-central is activated, then server.address is 192.168.1.120. If I don't activate all three, then the server.address is 192.168.1.100, and the environment is configured to use-to separate it.

Note: the spring.profiles attribute can be either a name or an expression.

2) @ Profile annotations are used

We often encounter the problem of dynamic selection of components, such as I have multiple access methods or selective activation of data sources. But I don't want to write if else back and forth, so @ Profile is an artifact, and his arrival makes our code more flexible.

For example, let's rewrite a configuration that belongs to the source:

/ / the first @ Configuration@Profile ("development") public class StandaloneDataConfig {@ Bean public DataSource dataSource () {return new EmbeddedDatabaseBuilder () .setType (EmbeddedDatabaseType.HSQL) .add Script ("classpath:com/bank/config/sql/schema.sql") .addScript ("classpath:com/bank/config/sql/test-data.sql") .build () }} / / second @ Configuration@Profile ("production") public class JndiDataConfig {@ Bean (destroyMethod= ") public DataSource dataSource () throws Exception {Context ctx = new InitialContext (); return (DataSource) ctx.lookup (" java:comp/env/jdbc/datasource ");}}

In this way, we can activate different logic according to different configurations, and it will be even more beautiful if we can match it with a remote configuration center.

7. The problem of YAML

1) YAML has many advantages, but it must also have some minor problems. That is, YAML files cannot be configured to load using the @ PropertySource annotation by default. If you don't want to make redundant modifications, then honestly create a properties file to use.

2) configuring multi-environment configuration information in YAML sometimes has strange problems, such as the following:

Application-dev.yml

Server: port: 8000---spring: profiles: "! test" security: user: password: "secret"

If I load-- spring.profiles.active=dev when I start the app at this time, then I should normally get security.user.password = secret, but this is not the case.

Because we use xxx-dev.yml on the configuration file name, we will find the application-dev.yml file directly when the application is loaded. At this point, the multi-environment configuration in our configuration file is invalid.

So no matter how many environments are configured, we either choose xxx-dev.yml or xxx-pro.yml, or we choose to configure multiple environments in one file. You can only choose one of the two to avoid disgusting problems.

8. Object attribute binding

Sometimes we have a set of properties of the same type to load, and it would be exhausting to use @ Value. Here Spring Boot provides us with a convenient way to use a class to uniformly load the required variables.

For example:

/ / attribute class package com.example;import java.net.InetAddress;import java.util.ArrayList;import java.util.Collections;import java.util.List;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties ("acme") public class AcmeProperties {private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security () Public boolean isEnabled () {...} public void setEnabled (boolean enabled) {...} public InetAddress getRemoteAddress () {...} public void setRemoteAddress (InetAddress remoteAddress) {...} public Security getSecurity () {...} public static class Security {private String username; private String password; private List roles = new ArrayList (Collections.singleton ("USER")) Public String getUsername () {...} public void setUsername (String username) {...} public String getPassword () {...} public void setPassword (String password) {...} public List getRoles () {...} public void setRoles (List roles) {...}

At this point, I configure the following properties in application.yml, and Spring Boot will help us bind the properties directly to the AcmeProperties class.

Acme.enabled = falseacme.remote-address=127.0.0.1acme.security.username=xxx

Because @ EnableConfigurationProperties only helps us to make a declaration, we need to cooperate with * * @ Configuration**, in actual use, such as the following configuration, so that we can use @ Resource for attribute injection after configuration.

@ Configuration (proxyBeanMethods = false) @ EnableConfigurationProperties (AcmeProperties.class) public class MyConfiguration {} 9, loose binding rules

It was mentioned above that @ ConfigurationProperties can help us bind object properties, but it actually provides us with fairly loose binding rules in Spring Boot.

For example, context-path binds to the contextPath attribute, PORT binds to the port attribute, and then goes on to create a Demo.

@ ConfigurationProperties (prefix= "acme.my-project.person") public class OwnerProperties {private String firstName; public String getFirstName () {return this.firstName;} public void setFirstName (String firstName) {this.firstName = firstName;}}

Taking the above code as an example, we can bind properties to firstName parameters in all of the following four configuration forms in application.yml.

Acme.my-project.person.first-name

Acme.myProject.person.firstName

Acme.my_project.person.first_name

ACME_MYPROJECT_PERSON_FIRSTNAME

Of course, in order to unify without problems, it is recommended to use lowercase for attribute declarations such as acme.my-project.person.first-name.

10. Attribute binding check

On the property class declared by @ ConfigurationProperties, we can add * * @ Validated** to verify the configuration properties.

ConfigurationProperties (prefix= "acme") @ Validatedpublic class AcmeProperties {@ NotNull private InetAddress remoteAddress; @ Valid private final Security security = new Security (); / /. Getters and setters public static class Security {@ NotEmpty public String username; / /... Getters and setters}} "what are the Spring Boot configuration methods?" this is the end of the introduction. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report