Spring Boot中的Properties的使用详解

作者:flydean 时间:2021-07-02 07:25:22 

简介

本文我们将会讨怎么在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

来源:https://segmentfault.com/a/1190000021714088

标签:Spring,Boot,Properties
0
投稿

猜你喜欢

  • Java8通过Function获取字段名的方法(获取实体类的字段名称)

    2021-05-23 12:24:19
  • Spring IOC:CreateBean环节中的流程转换

    2022-06-10 12:28:31
  • 优化spring boot应用后6s内启动内存减半

    2021-09-13 02:47:59
  • C#开发中常用的加密解密方法汇总

    2021-09-06 23:35:49
  • Thymeleaf 3.0 自定义标签方言属性的实例讲解

    2023-03-24 20:40:23
  • Android iOS常用APP崩溃日志获取命令方法

    2022-06-15 08:07:14
  • C语言实现双向链表

    2023-05-30 08:02:24
  • 聊聊java中引用数据类型有哪些

    2022-01-10 11:59:10
  • SpringBoot整合TKMyBatis实现单表增删改查操作

    2022-01-30 19:52:28
  • Mybatis返回插入的主键问题解决方案

    2023-05-06 02:58:03
  • Java压缩文件工具类ZipUtil使用方法代码示例

    2022-11-26 02:21:32
  • Winform项目中TextBox控件DataBindings属性

    2023-03-29 15:25:15
  • Spring Security OAuth 自定义授权方式实现手机验证码

    2021-10-03 23:30:27
  • 使用java8 API遍历过滤文件目录及子目录和隐藏文件示例详解

    2023-08-29 02:42:29
  • JAVA基于Arrays.sort()实现数组升序和降序

    2022-03-11 13:09:48
  • 微信开发--企业转账到用户

    2023-01-06 00:52:41
  • Java 实战项目之小说在线阅读系统的实现流程

    2022-01-31 07:41:49
  • Java多线程案例之单例模式懒汉+饿汉+枚举

    2021-11-07 05:18:01
  • Java实现人机猜拳小游戏

    2023-10-07 16:11:37
  • Java线程同步方法实例总结

    2022-08-20 20:35:08
  • asp之家 软件编程 m.aspxhome.com