从配置文件中获取属性应该是SpringBoot开发中最为常用的功能之一,但就是这么常用的功能,仍然有很多开发者抓狂~今天带大家简单回顾一下这六种的使用方式:
Obtaining properties from the configuration file should be one of the most commonly used functions in SpringBoot development, but even though this is a very common function, there are still many developers | |
---|---|
Today, let's take a simple review of the six usage methods: | DescriptionEnvironment objectEnvironment is the core environment configuration interface of springboot, it provides simple methods to access application properties, including system properties, operating system environment variables, command line parameters, and properties defined in application configuration files, etc.,Using the Environment method to obtain configuration property values is very simple, just inject the Environment class and call its method |
@Value | getProperty(property key)It can be done@Value annotation is provided by the Spring framework for injecting configuration property values, it can be used on class member variables, method parameters, and constructor parameters, during the application startup, Beans annotated with @Value will be instantiated. All Beans that use the @Value annotation will be added to the PropertySourcesPlaceholderConfigurer's post-processor collection. When the post-processor starts to execute, it will read all the values annotated with @Value in the Bean, and assign the parsed property values to the member variables, method parameters, and constructor parameters annotated with @Value through reflection.Important!!! |
@ConfigurationProperties | ⚠️Attention ① When using the @Value annotation, make sure that the injected property values have been loaded into the Spring container, otherwise it will cause the injection to fail; ② It is recommended to give a default value when referencing variables to avoid errors such as 'missing configuration' during startup; ③ throughSpringBoot provides a more convenient way to handle property values in configuration files, which can automatically bind and convert types through mechanisms such as automatic binding and type conversion, and obtain object property values in a dependency injection manner, please note that do not use the new way to create objects to obtain their properties.Specify a prefix |
@PropertySources | The implementation principle of the @PropertySources annotation is relatively simple, the application scans all classes annotated with this annotation at startup, and automatically binds the property set in the annotation to a Bean object.Specify a custom configuration fileThe path specified will load the content of the configuration file under the specified path into the Environment, so that the property values defined in it can be obtained through the @Value annotation or the Environment.getProperty() method. By default, it is limited to reading the content of properties files, and if you want to load the content of yaml files, you can customize the factory adapter and specify the specific usage of the factory |
YamlPropertiesFactoryBean object | Limited to reading yaml files only,Use the @Value annotation or Environment.getProperty() method to obtain the defined property values. |
JAVA Native | Load properties from the configuration file using java.util.Properties |
Chapter 1: Environment

Call the method getProperty(属性key) of the Environment class by injecting the Environment class.
@Slf4j@SpringBootTestpublicclassEnvironmentTest{@ResourceprivateEnvironmentenv;@Testpublicvoidvar1Test(){Stringvar1 =env.getProperty("env.var1");log.info("Configuration content obtained by Environment: {}",var1);}}
Chapter 2: @Value Annotation
Just add the annotation @Value("${env.var1}") to the variable, and the @Value annotation will automatically inject the value of the property env.var1 in the configuration file into the var1 field.
@Slf4j@SpringBootTestpublicclassEnvVariablesTest{@Value("${env.var1}")privateStringvar1;@Testpublicvoidvar1Test(){log.info("Configuration file properties: {}",var1);}}
Chapter 3: @ConfigurationProperties Annotation
Add configuration items to the application.yml configuration file:
env:
var1: variable value 1
var2: variable value 2
Create a MyConf class to carry all configuration properties with the prefix of env.
@Data@Configuration@ConfigurationProperties(prefix ="env")publicclassMyConf{privateStringvar1;privateStringvar2;}
To use the values of var1 and var2 properties, inject the MyConf object into the dependent object where needed.
@Slf4j@SpringBootTestpublicclassConfTest{@ResourceprivateMyConfmyConf;@TestpublicvoidmyConfTest(){log.info("The configuration content obtained by @ConfigurationProperties annotation: {}",JSON.toJSONString(myConf));}}
Chapter 4: @PropertySources Annotation
Create a custom configuration file named important.properties under the directory src/main/resources and add two properties.
env.var1=variable value 1
env.var2=variable value 2
Add the @PropertySources annotation to the class that needs to use a custom configuration file. Specify the path to the custom configuration file in the value attribute of the annotation. Multiple paths can be specified, separated by commas.
@Data@Configuration@PropertySources({@PropertySource(value ="classpath:important.properties",encoding ="utf-8"),@PropertySource(value ="classpath:important.properties",encoding ="utf-8")})publicclassPropertySourcesConf{@Value("${env.var1}")privateStringvar1;@Value("${env.var2}")privateStringvar2;}
Five, YamlPropertiesFactoryBean loads YAML files
@ConfigurationpublicclassMyYamlConfig{@BeanpublicstaticPropertySourcesPlaceholderConfigureryamlConfigurer(){PropertySourcesPlaceholderConfigurerconfigurer =newPropertySourcesPlaceholderConfigurer();YamlPropertiesFactoryBeanyaml =newYamlPropertiesFactoryBean();yaml.setResources(newClassPathResource("test.yml"));configurer.setProperties(Objects.requireNonNull(yaml.getObject()));returnconfigurer;}}
You can obtain the attribute values defined in it through the @Value annotation or Environment.getProperty() method.
@Slf4j@SpringBootTestpublicclassYamlTest{@Value("${env.var3}")privateStringvar3;@TestpublicvoidmyYamlTest(){log.info("Yaml obtain configuration content:{}",var3);}}
Six, JAVA native reading
@Slf4j@SpringBootTestpublicclassCustomTest{@TestpublicvoidcustomTest(){Propertiesprops =newProperties();try{InputStreamReaderinputStreamReader =newInputStreamReader(this.getClass().getClassLoader().getResourceAsStream("test.properties"),StandardCharsets.UTF_8);props.load(inputStreamReader);}catch(IOExceptione1){System.out.println(e1);}log.info("Properties Name:"+props.getProperty("env.appName"));}}
Author: JD Retail, Ma Hongwei
Source: JD Cloud Developer Community. Please indicate the source when转载.

评论已关闭