Home > Mobile >  spring boot read property value from file content (not property file)
spring boot read property value from file content (not property file)

Time:02-04

Is there a way to inject the value of a property from file content?

In my case i want to read a public certificate:

@ConstructorBinding
@ConfigurationProperties(prefix = "certificate")
@Value
public class Certificate {
    String publicKey;


}

The certificate is in a file with content like

-----BEGIN CERTIFICATE-----
MIIC3DCCAcSgAwIBAgIGAYYWvEf6MA0GCSqGSIb3DQEBCwUAMC8xLTArBgNVBAMM
JDhjOGVmNjQxLTEwMGEtNDUxMi1iOTFhLWM3Mzc5NDcwMTdjMzAeFw0yMzAyMDMx
...
4/eJiZvtUhlPTZAeBCbmwHhLFufMRrYtOje/JLDcXFUhF4Ypb6BITbbWijJ7oMqP
1Amyt3eKiVhFdIVk1U4gp19wda4oeKP 5gaPTvAlYrN EWdC1lUDRBipcM5zioFk
CwELjzRA2Dzg059g93NN7Q==
-----END CERTIFICATE-----

Currently i have 2 ways to load this as property:

  • load it in env variable with shell CERTIFICATE_PUBLIC_KEY="$(cat ./certs/device-cert.pem)" - need to run before
  • change the file to a property file beginning with certificate.publicKey= and adding "\n" at every line end and adding it as additional property source

Is there a way to load the file content directly into a property on start? At the moment i don't want to loose the Spring Boot Property feature - because it is really flexible. If not possible i can of course just load the file and use its content.

CodePudding user response:

It is possible with Spring. You can add the following option to your application properties file:

spring:
  config:
    import: configtree:/specify_the_path_where_your_file_is_located/

Then you should put your public key file to that location and give a name to this file according to your desired configuration properties:

certificate.publicKey

And you're done here! During application startup the content of that file will be injected to that property and will be both accesible from your configuration properties or from Environment bean

  • Related