Spring Boot中的Properties的使用详解

简介

本文我们将会讨怎么在Spring Boot中使用Properties。使用Properties有两种方式,一种是java代码的注解,一种是xml文件的配置。本文将会主要关注java代码的注解。

使用注解注册一个Properties文件

注册Properties文件我们可以使用@PropertySource 注解,该注解需要配合@Configuration 一起使用。

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
  //...
}

我们也可以使用placeholder来动态选择属性文件:

@PropertySource({
 "classpath:persistence-${envTarget:mysql}.properties"
})
@PropertySource也可以多次使用来定义多个属性文件:

@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
  //...
}

我们也可以使用@PropertySources来包含多个@PropertySource:

@PropertySources({
  @PropertySource("classpath:foo.properties"),
  @PropertySource("classpath:bar.properties")
})
public class PropertiesWithJavaConfig {
  //...
}

使用属性文件

最简单直接的使用办法就是使用@Value注解:

@Value( "${jdbc.url}" )
private String jdbcUrl;

我们也可以给属性添加默认值:

@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;

如果要在代码中使用属性值,我们可以从Environment API中获取:

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

Spring Boot中的属性文件

默认情况下Spring Boot 会读取application.properties文件作为默认的属性文件。当然,我们也可以在命令行提供一个不同的属性文件:

java -jar app.jar --spring.config.location=classpath:/another-location.properties

如果是在测试环境中,我们可以使用@TestPropertySource 来指定测试的属性文件:

@RunWith(SpringRunner.class)
@TestPropertySource("/foo.properties")
public class FilePropertyInjectionUnitTest {

  @Value("${foo}")
  private String foo;

  @Test
  public void whenFilePropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}

除了属性文件,我们也可以直接以key=value的形式:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"foo=bar"})
public class PropertyInjectionUnitTest {

  @Value("${foo}")
  private String foo;

  @Test
  public void whenPropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}

使用@SpringBootTest,我们也可以使用类似的功能:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class)
public class SpringBootPropertyInjectionIntegrationTest {

  @Value("${foo}")
  private String foo;

  @Test
  public void whenSpringBootPropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}

@ConfigurationProperties

如果我们有一组属性,想将这些属性封装成一个bean,则可以考虑使用@ConfigurationProperties。

@ConfigurationProperties(prefix = "database")
public class Database {
  String url;
  String username;
  String password;

  // standard getters and setters
}

属性文件如下:

database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar

Spring Boot将会自动将这些属性文件映射成java bean的属性,我们需要做的就是定义好prefix。

yaml文件

Spring Boot也支持yaml形式的文件,yaml对于层级属性来说更加友好和方便,我们可以看下properties文件和yaml文件的对比:

database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
secret: foo
database:
 url: jdbc:postgresql:/localhost:5432/instance
 username: foo
 password: bar
secret: foo

注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,则必须指定properties文件。

Properties环境变量

我们可以这样传入property环境变量:

java -jar app.jar --property="value"

~~shell

java -Dproperty.name="value" -jar app.jar

或者这样:
export name=value
java -jar app.jar

环境变量有什么用呢? 当指定了特定的环境变量时候,Spring Boot会自动去加载application-environment.properties文件,Spring Boot默认的属性文件也会被加载,只不过优先级比较低。

## java代码配置

除了注解和默认的属性文件,java也可以使用PropertySourcesPlaceholderConfigurer来在代码中显示加载:

@Bean
public static PropertySourcesPlaceholderConfigurer properties(){

PropertySourcesPlaceholderConfigurer pspc
 = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[ ]
 { new ClassPathResource( "foo.properties" ) };
pspc.setLocations( resources );
pspc.setIgnoreUnresolvablePlaceholders( true );
return pspc;
}

本文的例子可以参考:https://github.com/ddean2009/learn-springboot2/tree/master/springboot-properties](https://github.com/ddean2009/learn-springboot2/tree/master/springboot-properties

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • spring boot使用i18n时properties文件中文乱码问题的解决方法

    国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式.它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素.换言之,应用程序的功能和代码设计考虑在不同地区运行的需要,其代码简化了不同本地版本的生产.开发这样的程序的过程,就称为国际化. 在springboot使用i18n进行国际化文件配置时,文件名为messages_zh_CN.properties的文件中填写中文信息,当使用浏览器进行访问时,出现中文乱码,此时在idea中进行修改setting

  • 详解Spring Boot配置文件application.properties

    在 Spring Boot 中,配置文件有两种不同的格式,一个是 properties ,另一个是 yaml . 虽然 properties 文件比较常见,但是相对于 properties 而言,yaml 更加简洁明了,而且使用的场景也更多,很多开源项目都是使用 yaml 进行配置(例如 Hexo).除了简洁,yaml 还有另外一个特点,就是 yaml 中的数据是有序的,properties 中的数据是无序的,在一些需要路径匹配的配置中,顺序就显得尤为重要(例如我们在 Spring Cloud

  • Spring Boot2.0 @ConfigurationProperties使用详解

    引言 Spring Boot的一个便捷功能是外部化配置,可以轻松访问属性文件中定义的属性.本文将详细介绍@ConfigurationProperties的使用. 配置项目POM 在pom.xml中定义Spring-Boot 为parent <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>

  • 详解spring boot 使用application.properties 进行外部配置

    application.properties大家都不陌生,我们在开发的时候,经常使用它来配置一些可以手动修改而且不用编译的变量,这样的作用在于,打成war包或者jar用于生产环境时,我们可以手动修改环境变量而不用再重新编译. spring boo默认已经配置了很多环境变量,例如,tomcat的默认端口是8080,项目的contextpath是"/"等等,可以在这里看spring boot默认的配置信息http://docs.spring.io/spring-boot/docs/curr

  • Spring Boot中配置文件application.properties使用

    一.配置文档配置项的调用 启动后在浏览器直接输入http://localhost:18080/user/test,就直接打印出配置文件中的配置内容. 二.绑定对象bean调用 有时候属性太多了,一个个绑定到属性字段上太累,官方提倡绑定一个对象的bean,这里我们建一个ConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = "com")来指明使用哪个 @ConfigurationProperties(prefix = &quo

  • spring boot application properties配置实例代码详解

    废话不多说了,直接给大家贴代码了,具体代码如下所示: # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # ========

  • spring boot使用properties定义短信模板的方法教程

    前言 通常我们做开发时候会遇到短信发送邮件发送之类的需求,发送内容往往会由客户提供一个模板,如果我们是在程序里拼接字符串来搞定这个模板,很明显是一种坑队友的做法.一般将模板放入properties文件中,使用的时候替换其中的一些变量即可. 本文我们使用springboot来实现根据模板发送短信验证码的功能,下面话不多说了,来一起看看详细的介绍吧. tips: 1.正则表达式 2.springboot读取properties文件 模板定义 将需要定义的短信模板都定义在msg.properties文

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • spring boot中的properties参数配置详解

    application.properties application.properties是spring boot默认的配置文件,spring boot默认会在以下两个路径搜索并加载这个文件 src\main\resources src\main\resources\config 配置系统参数 在application.properties中可配置一些系统参数,spring boot会自动加载这个参数到相应的功能,如下 #端口,默认为8080 server.port=80 #访问路径,默认为/

  • Spring Boot的properties配置文件读取

    我在自己写点东西玩的时候需要读配置文件,又不想引包,于是打算扣点Spring Boot读取配置文件的代码出来,当然只是读配置文件没必要这么麻烦,不过反正闲着也是闲着,扣着玩了. 具体启动过程以前的博客写过Spring Boot启动过程(一),这次入口在SpringApplication类中: private ConfigurableEnvironment prepareEnvironment( SpringApplicationRunListeners listeners, Applicatio

  • 在SpringBoot下读取自定义properties配置文件的方法

    SpringBoot工程默认读取application.properties配置文件.如果需要自定义properties文件,如何读取呢? 一.在resource中新建.properties文件 在resource目录下新建一个config文件夹,然后新建一个.properties文件放在该文件夹下.如图remote.properties所示 二.编写配置文件 remote.uploadFilesUrl=/resource/files/ remote.uploadPicUrl=/resource

  • SPRINGBOOT读取PROPERTIES配置文件数据过程详解

    这篇文章主要介绍了SPRINGBOOT读取PROPERTIES配置文件数据过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.使用@ConfigurationProperties来读取 1.Coffer entity @Configuration @ConfigurationProperties(prefix = "coffer") @PropertySource("classpath:config/coffer.p

  • 详解Spring Boot加载properties和yml配置文件

    一.系统启动后注入配置 package com.example.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframewo

随机推荐