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

How to read configuration in Spring Boot

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

Share

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

This article mainly shows you "how to read configuration in Spring Boot", the content is easy to understand, clear, hope to help you solve your doubts, let the editor lead you to study and learn "how to read configuration in Spring Boot" this article.

1 purpose

In this section, we will solve the following problems:

How do I read a configuration file using Spring Boot? What are the ways?

How to configure several commonly used data structures, such as strings, integers, List, Map? How do I read it?

How do I customize the path to the profile?

2 read profile

The default configuration file for Spring Boot comes in two formats: application.properties and application.yml.

The search order is to first look from application.properties, and then look for application.yml if you can't find it.

Priority: application.properties > application.yml.

First, add dependencies.

Maven:

Org.springframework.boot spring-boot-configuration-processor true

Gradle:

AnnotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'2.1 uses @ Value to read the configuration

The configuration is as follows:

Erwin.name= Feng Wenyi erwin.age=20erwin.sex= male erwin.english-name=Erwin Fengerwin.birthday=1992/02/26erwin.like=movie,game,music,tea,travelerwin.visitedCities= Bazhong, Jieyang, Guangzhou, Conghua, Chengdu, Sanya, Shanghai, Hangzhou, Beijing erwin.moreOther= {myWeb:' https://fengwenyi.com',github:'https://github.com/fengwenyi'}

The code is as follows:

Package com.fengwenyi.spring_boot_config_sample.config;import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Configuration;import java.util.*;/** * @ author Erwin Feng * @ since 2020-8-11 * / @ Data@Configurationpublic class ReadConfigByValue {@ Value ("${erwin.name}") private String name; @ Value ("${erwin.age}") private Integer age @ Value ("${erwin.sex}") private String sex; @ Value ("${erwin.english-name}") private String englishName; @ Value ("${erwin.birthday}") private Date birthday; @ Value ("${erwin.like}") private List likes; @ Value ("# {${erwin.visitedCities} '.split (',')}") private List visitedCities @ Value ("# {${erwin.moreOther}}") private Map moreOther;} 2.2 read the configuration using @ ConfigurationProperties

The configuration is as follows (properties format)

Author.name= Feng Wenyi author.age=20author.sex= male author.english-name=Erwin Fengauthor.birthday=1992/02/26author.like [0] = movieauthor.like [1] = gameauthor.like [2] = musicauthor.like [3] = teaauthor.like [4] = travelauthor.visitedCities= Bazhong, Jieyang, Guangzhou, Conghua, Chengdu, Sanya, Shanghai, Hangzhou, Beijing author.moreOther.myWeb= https://fengwenyi.comauthor.moreOther.github=https://github.com/fengwenyi

The configuration is as follows (yaml format)

Author: name: Feng Wenyi-yml age: 20 sex: male english-name: Erwin Feng birthday: 1992-02-26 like:-movie-game-music-tea-travel visitedCities: Bazhong, Jieyang, Guangzhou, Conghua, Chengdu, Sanya, Shanghai, Hangzhou, Beijing moreOther: myWeb: https://fengwenyi.com github: https://github.com/fengwenyi

The code is as follows:

Package com.fengwenyi.spring_boot_config_sample.config;import com.fasterxml.jackson.annotation.JsonFormat;import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Configuration;import java.io.Serializable;import java.util.Date;import java.util.List;import java.util.Map / * * @ author Erwin Feng * @ since 2020-8-12 * / @ Data@Configuration@ConfigurationProperties (prefix = "author") public class AuthorConfig implements Serializable {private static final long serialVersionUID = 9032405467573421607L; private String name; private Integer age; private String sex; private String englishName; @ JsonFormat (pattern = "yyyy/MM/dd") private Date birthday; private List like; private List visitedCities; private Map moreOther;}

The read data shows:

{"name": "Feng Wenyi", "age": 20, "englishName": "Erwin Feng", "birthday": "1992-02-26", "likes": ["movie", "game", "music", "tea", "travel"], "visitedCities": ["Bazhong", "Jieyang", "Guangzhou" "Conghua", "Chengdu", "Sanya", "Shanghai", "Hangzhou", "Beijing"], "moreOther": {"myWeb": "https://fengwenyi.com"," github ":" https://github.com/fengwenyi"} 2.3 obtain configuration information @ Autowired private Environment environment by injecting environment variables 3 @ Value usage 3.1 set default value

Format: @ Value ("${name:defaultValue}")

When the configuration file cannot find the configuration, the default value is returned, and if there is no default value, an error is reported.

3.2 you can read the property values of the system directly

For example: @ Value ("${java.home}")

D:\ Java\ Java8\ jdk1.8.0_251\ jre

3.3.It can be used on methods and parameters as a unit test / / unit test-reading the value of the configuration file @ Value ("${erwin.like}") public void testReadLike (String like, @ Value ("${erwin.sex}") String sex) {System.out.println ("1 steps = >" + like); System.out.println ("1 steps = >" + sex);}

Parameter like takes the value of @ Value ("${erwin.like}"). Parameter sex takes the value of @ Value ("${erwin.sex}"). After testing, multiple methods are executed in random order. Special note: this is only executed at startup, but when actually called, it is still the value passed in.

3.4 read the value of list

Method 1: configuration file:

Erwin.like=movie,game,music,tea,travel

Java Code:

@ Value ("${erwin.like}") private List likes

Method 2:

Erwin.visitedCities= Bazhong, Jieyang, Guangzhou, Conghua, Chengdu, Sanya, Shanghai, Hangzhou, Beijing

Java Code:

@ Value ("# {${erwin.visitedCities} '.split (',')}") private List visitedCities

3.5 read the value of Map

Configuration file:

Erwin.moreOther= {myWeb:' https://fengwenyi.com',github:'https://github.com/fengwenyi'}

Java Code:

@ Value ("# {${erwin.moreOther}}") private Map moreOther

3.6 read system properties

@ Value ("# {systemProperties}") private Map systemPropertiesMap

Assign @ Component@PropertySource ("classpath:values.properties") public class PriorityProvider {private String priority; @ Autowired public PriorityProvider (@ Value ("${priority:normal}") String priority) {this.priority = priority;} / / standard getter} 4 @ ConfigurationPropertiespackage com.fengwenyi.spring_boot_config_sample.config;import com.fengwenyi.spring_boot_config_sample.support.YamlPropertySourceFactory;import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties to the private attribute Import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import java.io.Serializable;/** * @ author Erwin Feng * @ since 2020-8-13 * / @ Data@Configuration@ConfigurationProperties (prefix = "db") / / @ PropertySource ({"classpath:config/db.properties"}) @ PropertySource (value = {"classpath:config/db.yml"}, factory = YamlPropertySourceFactory.class) public class DBConfig implements Serializable {private static final long serialVersionUID =-6527591545525817929L / * * Server address * / private String host; / * * Port * / private Integer port; / * * Database name * / private String dbName; / * * user name * / private String username; / * * password * / private String password;}

Configuration file:

Db: host: localhost port: 3306 db-name: test username: root password: 123456

Note: 1. @ Configuration indicates that this is a Spring configuration and will be injected into the Spring container. 2. @ ConfigurationProperties (prefix = "db") indicates that this class is associated with the configuration file, where prefix indicates the prefix. 3. @ PropertySource indicates the location of the configuration file. If there is no such configuration, it will be read from the default configuration file. The default configuration file is application.properties > application.yml. In addition, this default only supports files of type properties, so you need to configure factory. 4. @ PropertySource can also be used in conjunction with @ Value.

YamlPropertySourceFactory

Package com.fengwenyi.spring_boot_config_sample.support;import org.springframework.boot.env.YamlPropertySourceLoader;import org.springframework.core.env.PropertySource;import org.springframework.core.io.support.EncodedResource;import org.springframework.core.io.support.PropertySourceFactory;import java.io.IOException / * * @ author Erwin Feng * @ since 2020-8-13 * / public class YamlPropertySourceFactory implements PropertySourceFactory {@ Override public PropertySource createPropertySource (String name, EncodedResource resource) throws IOException {/ / returns the yaml attribute resource return new YamlPropertySourceLoader () .load (resource.getResource () .load (), resource.getResource ()) .get (0) }} above is all the content of the article "how to read configuration in Spring Boot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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