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


或者这样: ~~~shell
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

更多教程请参考 flydean的博客

Spring Boot中的Properties的更多相关文章

  1. Spring Boot中application.properties和application.yml文件

    application.properties和application.yml文件可以放在一下四个位置: 外置,在相对于应用程序运行目录的/congfig子目录里. 外置,在应用程序运行的目录里 内置, ...

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

    一.配置文档配置项的调用(application.properties可放在resources,或者resources下的config文件夹里) package com.my.study.contro ...

  3. springboot(十一):Spring boot中mongodb的使用

    mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置 ...

  4. Spring Boot Dubbo applications.properties 配置清单

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 与其纠结,不如行动学习.Innovate ,And out execute ! 』 本文 ...

  5. 在Spring Boot中使用数据缓存

    春节就要到了,在回家之前要赶快把今年欠下的技术债还清.so,今天继续.Spring Boot前面已经预热了n篇博客了,今天我们来继续看如何在Spring Boot中解决数据缓存问题.本篇博客是以初识在 ...

  6. 在Spring Boot中使用数据库事务

    我们在前面已经分别介绍了如何在Spring Boot中使用JPA(初识在Spring Boot中使用JPA)以及如何在Spring Boot中输出REST资源(在Spring Boot中输出REST资 ...

  7. 在Spring Boot中输出REST资源

    前面我们我们已经看了Spring Boot中的很多知识点了,也见识到Spring Boot带给我们的各种便利了,今天我们来看看针对在Spring Boot中输出REST资源这一需求,Spring Bo ...

  8. 初识在Spring Boot中使用JPA

    前面关于Spring Boot的文章已经介绍了很多了,但是一直都没有涉及到数据库的操作问题,数据库操作当然也是我们在开发中无法回避的问题,那么今天我们就来看看Spring Boot给我们提供了哪些疯狂 ...

  9. Spring Boot 中的静态资源到底要放在哪里?

    当我们使用 SpringMVC 框架时,静态资源会被拦截,需要添加额外配置,之前老有小伙伴在微信上问松哥Spring Boot 中的静态资源加载问题:"松哥,我的HTML页面好像没有样式?& ...

随机推荐

  1. radio 单选按钮 选中多个

    <input type="radio" name="a"/> <input type="radio" name=" ...

  2. keras与卷积神经网络(CNN)实现识别minist手写数字

    在本篇博文当中,笔者采用了卷积神经网络来对手写数字进行识别,采用的神经网络的结构是:输入图片——卷积层——池化层——卷积层——池化层——卷积层——池化层——Flatten层——全连接层(64个神经元) ...

  3. flask-redirect

    flask-redirect from flask import Flask, url_for, request, redirect app = Flask(__name__) @app.route( ...

  4. IDEA使用技巧,如何在JSP中创建Servlet“小程序”

    步骤 1.新建一个java类,实现Servlet接口 2.实现接口中的抽象方法: 3.在web.xml文件中配置好servlet <web-app ......> <servlet& ...

  5. 安卓开发学习日记 DAY4——Button,ImageButton

    Button与ImageButton基本类似 也有类似于TextView和ImageView的区别 这里需要注意的是: 在你定义text属性的内容时,最好是在Values文件下的String.xml中 ...

  6. django中写分页

    1.引用函数import from django.core.paginator import Paginator 2.分页 page_obj = Paginator(Article.objects.a ...

  7. 三、ARP协议和ICMP协议

    一.ARP协议 网络设备有数据要发送到另一台网络设备时,必须要知道对方的网络层地址(IP).IP地址由网络层来提供,但是仅有IP地址是不够的,IP数据报文必须封装成帧才能通过数据链路进行发送.数据帧必 ...

  8. Go语言的GPM调度器是什么?

    我是平也,这有一个专注Gopher技术成长的开源项目「go home」 导读 相信很多人都听说过Go语言天然支持高并发,原因是内部有协程(goroutine)加持,可以在一个进程中启动成千上万个协程. ...

  9. Markdown自动生成目录

    Markdown自动生成目录 使用npm语法生成 1.安装npm 2.安装doctoc插件 3.执行生成 参考 Markdown自动生成目录 使用npm语法生成 1.安装npm 我的系统是deepin ...

  10. tf.nn.sigmoid_cross_entropy_with_logits 分类

    tf.nn.sigmoid_cross_entropy_with_logits(_sentinel=None,,labels=None,logits=None,name=None) logits和la ...