Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring-Boot: How to load a keystore resource file either from the classpath or from the file system?

My spring-boot application requires access to private keys via a Java keystore. For testing, I would like to use a test keystore that is available on the classpath (so I can easily execute the application as part of an integration test), while in production I would like to use a keystore from some external volume (e.g., mounted inside a container as k8 secret).

I know that the spring-boot @Value annotation allows me to inject a resource. However, I don’t see how it can be made dynamic to respect the spring environment (e.g., test or production). Does spring-boot provide an out-of-the-box way to solve the above problem, or do I need to write my own bean to load the correct keystore depending on the deployment environment?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a property for the resource path and set that property values in your application props differently based on an active profile.

@Value("${my.resource.path:#{null}}")
private Resource myResource;

application.yml:

spring:
    config:
        activate:
            on-profile: test
my.resource.path: 'classpath:test/path/keystore.jks'

---
spring:
    config:
        activate:
            on-profile: prod
my.resource.path: 'prod/path/keystore.jks'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading