java - Spring 启动: How to set spring properties dynamically

标签 java spring spring-boot properties

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

因此,这些将是 spring 定义的属性,可从 application.properties 中使用。我只是想根据一些逻辑从代码中设置它们。

对于非 Spring 应用程序,我仍然有一些想法,它们可以作为应用程序、 session 或上下文属性传递,但我不知道这在 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 类向应用程序添加属性。

现在,这些属性已在程序中定义,您可以根据需要应用条件并更改属性值。

关于java - Spring 启动: How to set spring properties dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461061/

相关文章:

java - 在Spring JDBC中,如何在语句上设置RESULT SET HOLDABILITY?

java - Spring Boot 从 Runtime.getRuntime().exec() 开始,一直等待,直到调用者进程终止

java - Spring 集成: how to send a Byte Array as POST parameter with an http:outbound-gateway?

JAVA SPRING BOOT - 在运行时交换环境变量的内容

java - Spring Boot ssl 信任库属性不起作用

spring-boot - 数据库 "C:/data/sample"未找到,如果 EXISTS=true,所以我们无法自动创建它 - Spring Boot 中的错误

java - 安卓.view.InflateException : Binary XML file line #13: Error inflating class ViewPager

java - 如何启动带有附加图像的电子邮件 Intent ?

java 。 IntelliJ IDEA 热插拔

java - ArrayAdapter 正在更改 CheckBox 的值