如何指定 Spring Boot 应用程序仅访问 Spring Cloud 配置服务器中其他文件中的特定
.properties
文件。
我的Spring Cloud Config有以下文件:
application.properties
,order-dev.properties
,inventory-dev.properties
,
我所有的数据库和消息传递属性都在 order-dev 和 inventory-dev 文件中。
现在我希望将这些属性移动到
orderdb-dev
、inventorydb-dev
、ordermsg-dev
和 inventorymsg-dev
文件。
如何配置我的
order
和 inventory
服务以从 orderdb-dev
、inventorydb-dev
、ordermsg-dev
和 inventorymsg-dev
文件中选择属性?我一直在四处寻找同样的房产。翻阅官方文档,感觉失落。任何帮助将不胜感激。
在 resources 文件夹下添加 bootstrap.yml 文件。然后添加以下属性。
spring:
application:
name: order
cloud:
config:
name: ${spring.application.name}, orderdb, ordermsg
profile: dev
这样,它将首先从 order-dev.properties 文件加载属性。然后是 orderdb-dev.properties,然后是 ordermsg-dev.properties。
假设你的配置是
myboot.properties
。--spring.config.name
:
$ java -jar myproject.jar --spring.config.name=myboot
在命令行中我们指定
myboot
但 Spring Boot 将搜索 myboot.properties
。许多属性文件可以添加逗号分隔,如下所示:
$ java -jar myproject.jar --spring.config.name=myboot,myboot2,myboot3
现在
myboot3.properties
中的属性将覆盖 myboot2.properties
中的属性,但 myboot2.properties
将会覆盖 myboot.properties
中的属性。
另一个选项,完整的配置名称在
--spring.config.location
中。现在文件名必须包含文件扩展名。 Spring Boot 使用扩展来猜测配置语法。未知的扩展会产生错误:
$ java -jar myproject.jar --spring.config.location=classpath:/myboot.properties
也可以指定多个配置,以逗号分隔。
或者可以在源代码中实现完全相同的效果,而无需更改命令行:
@SpringBootApplication
public class MyBoot {
public static void main(String[] args) {
SpringApplication.run(
new Class<?>[] {MyBoot.class, MyController.class},
new String[]{"--spring.config.name=myboot"});
@SpringBootApplication
public class MyBoot {
public static void main(String[] args) {
SpringApplication.run(
new Class<?>[] {MyBoot.class, MyController.class},
new String[]{"--spring.config.location=classpath:/myboot.properties"});
或者您可能想避免删除现有的命令行参数:
@SpringBootApplication
public class MyBoot {
public static void main(String[] args) {
String[] newArgs = Stream.concat
(
Arrays.stream(args),
Arrays.stream(new String[]
{"--spring.config.location=classpath:/myboot.properties"})
)
.toArray(String[]::new);
SpringApplication.run(new Class<?>[] {SpringBootMVCSample.class, SpringBootMVCControllerSample.class}, newArgs);
所以,上面的代码只是一个想法,可能不够灵活,根据需要灵活调整。