应用程序属性中占位符的春季启动用法 [英] spring boot usage of placeholder in application properties
问题描述
我已经编写了一个使用mysql(5.7版)的简单的Spring Boot应用程序(版本springboot 2.0).
I have written a simple spring boot application(version springboot 2.0) which uses mysql(version 5.7).
application.properties 代码段
spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username = testuser
spring.datasource.password = testpassword
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
当我在本地运行它时,它工作正常. 如果我想在docker中运行此春季启动应用程序,则可以更改
When I run it locally, it works fine. If I want to run this spring boot application in docker then I can change
spring.datasource.url = jdbc:mysql://mysql-container:3306/test?useSSL=false
mysql-container使用dockerhub上的mysql:5.7镜像运行.
但是,我想从某些占位符属性文件中更改主机的值.这样看起来像:
However I want to change value of host from some placeholder properties file. so that this looks something like:
spring.datasource.url = jdbc:mysql://${MYSQL_HOST}:3306/test?useSSL=false
注意:我不确定占位符格式.是$ {MYSQL_HOST}还是@ MYSQL_HOST @吗?
note: I am not sure about placeholder format. Is it ${MYSQL_HOST} or @MYSQL_HOST@ ?
您可以将此占位符文件命名为 placeholder.properties 或 placeholder.conf 或 .env 或其他任何名称.该文件的内容应类似于:
you can name this placeholder file as placeholder.properties or placeholder.conf or .env or anything. The content of that file should be something like:
MYSQL_HOST=localhost
或
MYSQL_HOST=some ip address
我可以创建.env或.env.test或.env.prod,并且可以根据要在其中运行应用程序的位置来引用该env文件.
I can create .env or .env.test or .env.prod and I can refer that env file based on where I want to run application.
更新-
我有两个问题:
-
我应该在哪里保存placeholder.properties?是在/config/下还是在某些特定目录下?
Where should I keep placeholder.properties? Is it under /config/ or under some specific directory?
如何在application.properties中调用占位符?
how to invoke placeholder inside application.properties ?
有人可以建议吗?
推荐答案
感谢@Raheela Aslam和@ paulsm4的回答,还有更多研究发现了这个问题.
Thanks to answers by @Raheela Aslam and @paulsm4 and some more research found the issue.
我想要实现的目标:
- 在docker中部署springboot应用程序,然后将其部署到kubernetes.
- 我正在使用minikube进行本地测试,并希望将minikube ip传递到数据源url.
我如何修复它:
我分别为mysql_user,mysql_password和mysql_host创建了configmap.
I created configmap for mysql_user, mysql_password, mysql_host with respective values.
kubectl create configmap mysql-config \
--from-literal=mysql_user=testuser \
--from-literal=mysql_password=testuserpass \
--from-literal=mysql_user=$(minikube ip)
并在application.properties中使用了以下内容
and used these inside application.properties something like below
spring.datasource.url = jdbc:mysql://${MYSQL_HOST}:3306/test?useSSL=false
spring.datasource.username = ${MYSQL_USER}
spring.datasource.password = ${MYSQL_PASSWORD}
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
,然后在Deployment.yaml中将configmap值用于kubernetes. 然后开始部署服务.
and then used configmap values in deployment.yaml for kubernetes. Then did start service for deployment.
这篇关于应用程序属性中占位符的春季启动用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!