Spring Boot - Key Store Password set in Code

Right, figured it out. Was on the wrong track. What I should have done was the following:

@Component
public class KeystoreInit {

    private final Environment environment;

    @Autowired
    public KeystoreInit(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public ServerProperties serverProperties() {
        final ServerProperties serverProperties = new ServerProperties();
        final Ssl ssl = new Ssl();
        final String keystorePassword = getKeystorePassword();
        ssl.setKeyPassword(keystorePassword);
        System.setProperty("server.ssl.key-store-password", keystorePassword);
        serverProperties.setSsl(ssl);
        return serverProperties;
    }

    private String getKeystorePassword() {
        // ...
    }

}

The idea here is that we're creating the initial ServerProperties bean. This bean is then loaded instead of a fresh ServerProperties, so our Ssl with the keystore password is set there already. This isn't overridden since we don't set server.ssl.key-store-password in our application.yml.

We @Autowire the Environment so that we can access out server.ssl.key-store-label property (which I had previously created), use that to load our actual server.ssl.key-store-password property, and then set that via System properties so that it can be accessed elsewhere in the application.


  • spring boot:2.3.1.RELEASE
  • you need to add @Primary at method otherwise it will Start error.What I should have done was the following:
@Component
public class KeystoreInit {

    private final Environment environment;

    @Autowired
    public KeystoreInit(Environment environment) {
        this.environment = environment;
    }

    @Bean
    @Primary
    public ServerProperties serverProperties() {
        final ServerProperties serverProperties = new ServerProperties();
        final Ssl ssl = new Ssl();
        final String keystorePassword = getKeystorePassword();
        ssl.setKeyPassword(keystorePassword);
        System.setProperty("server.ssl.key-store-password", keystorePassword);
        serverProperties.setSsl(ssl);
        return serverProperties;
    }

    private String getKeystorePassword() {
        // ...
    }
}