[英]spring boot application.properties value from bean data
I am working with spring boot.我正在使用 spring 启动。 I have properties defined in application.yml.
我在 application.yml 中定义了属性。
spring:
datasource:
username: username
password: password
username and password values are stored externally which program fetches during startup.用户名和密码值存储在外部,由程序在启动期间获取。 let's say the bean which fetches them during startup is
dbConfig
假设在启动期间获取它们的 bean 是
dbConfig
How can I inject values from dbConfgig
to application.yml?如何将值从
dbConfgig
注入到 application.yml?
I am using spring-data-jpa autoconfigure which automatically connects to database at startup.我正在使用 spring-data-jpa 自动配置,它会在启动时自动连接到数据库。 I want these values to be loaded to application.yml before spring connects to database.
我希望在 spring 连接到数据库之前将这些值加载到 application.yml。
I think that first, you must create a thread to detect the change at your db Config file
and then may you must re-init your bean (data source) to make your change effect.我认为首先,您必须创建一个线程来检测您的
db Config file
中的更改,然后您可能必须重新初始化您的 bean(数据源)以使您的更改生效。
See: how-to-reinitialize-a-spring-bean请参阅: 如何重新初始化 spring-bean
There is no need to inject the user/password in application.yml
.无需在
application.yml
中注入用户/密码。 You can set them programmatically like this:您可以像这样以编程方式设置它们:
@Configuration
public class DataSourceConfig {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
// Take the values from external source, then set them
dataSourceBuilder.username("username");
dataSourceBuilder.password("password");
return dataSourceBuilder.build();
}
}
You may also try spring cloud to store properties.也可以尝试spring云存储属性。 And you can then use with the help of placeholders.
然后您可以在占位符的帮助下使用。
https://cloud.spring.io/spring-cloud-config/reference/html/ https://cloud.spring.io/spring-cloud-config/reference/html/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.