java - spring boot:如何动态设置弹簧属性
问题描述
在 spring boot 应用程序的 application.properties 中可以定义很多属性。
但我想传递属性来配置 ssl 从代码内部弹出。
server.ssl.enabled=true
# The format used for the keystore
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=keys/keystore.jks
# The password used to generate the certificate
server.ssl.key-store-password=changeit
# The alias mapped to the certificate
server.ssl.key-alias=tomcat
因此,这些将是从 application.properties 使用的 spring 定义的属性。我只想根据一些逻辑从代码中设置它们。
对于非 spring 应用程序,我仍然有一些想法,它们可以作为应用程序、会话或上下文属性传递,但我不知道它在 spring 中是如何工作的。
任何帮助,将不胜感激。
解决方案
由于您知道在 Spring Boot 应用程序中启用 SSL 的属性。您可以在 Spring Boot 应用程序中以编程方式传递这些属性,如下所示:
@SpringBootApplication
public class SpringBootTestApplication {
public static void main(String[] args) {
// SpringApplication.run(SpringBootTestApplication.class, args);
Properties props = new Properties();
props.put("server.ssl.key-store", "/home/ajit-soman/Desktop/test/keystore.p12");
props.put("server.ssl.key-store-password", "123456");
props.put("server.ssl.key-store-type", "PKCS12");
props.put("server.ssl.key-alias", "tomcat");
new SpringApplicationBuilder(SpringBootTestApplication.class)
.properties(props).run(args);
}
}
如您所见,我已将其注释掉:
SpringApplication.run(SpringBootTestApplication.class, args);
并使用SpringApplicationBuilder
类向应用程序添加属性。
现在,这些属性已在程序中定义,您可以根据需要应用条件并更改属性值。
推荐阅读
- javascript - 如何添加错误处理以检查输入是否是单独函数中的数字
- c# - 如何通过c#将用户控件从另一个用户控件带到前面
- php - 用于登录的标准正确 ajax 响应
- java - Java 嵌套的 while 循环无法按预期运行
- r - rbokeh,将图例添加到直方图
- python - 简化动态列表中字符串的修改?
- android - 如何在mainActivity中设置ExpandableListView的childView
- c++ - 为什么 std::string[] 数组的 size() 函数返回的参数数量不正确
- r - 访问数据框列中列表中的特定实例,并计算列表长度 - R
- sql - 如何使用 ORACLE SQL 从另一个实例中的同一个表中插入数据