3

I am using @PropertySource to configure a Configuration class:

@Configuration
@PropertySource("classpath:/mongo-${env}.properties")
public class MongoConfiguration {

mongo-${env}.properties files are located in the classpath. This works fine.

I am now externalizing configuration to Git with Spring Cloud Config: All application.yml files have been migrated. However I don't know if it is possible and how to externalize property files like the one declared in @PropertySource.

What I did: I tried to rename mongo-prod.properties to application-prod.properties in Git. Then I changed the @PropertySource to:

@PropertySource("file:///C://.../config-repo/application-prod.properties")

which is the local copy of the repository. This works but this is just an hardcoded solution.

Is there a cleaner solution?

Mykeul
  • 498
  • 1
  • 6
  • 20

1 Answers1

3

You can load properties using @ConfigurationProperties annotation Assuming you have setup your config server correctly.

Example assume your service name is customer-service and wanted to get properties files from config server.

Step 1 add customer-properties in you git repo. You can also add environment specific properties like

customer-qa.properties ,customer-dev.properties

Now to load these properties

@Component
@ConfigurationProperties("customer-service")
@Data
public class CustomerServiceConfigurations {

    private String somePropertyname;

} 

For more details please check below example Config Server

Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
  • I wanted to keep using PropertySource annotation and have separate files for separate property group like mongo-${env}.properties for mongo properties etc. The solution you described worked for me too, even no need for ConfigurationProperties annotation. Since for this specific example, the configuration is needed by multiple microservices, I copied those properties in the "common" application-prod.yml in Git. – Mykeul May 21 '19 at 15:05
  • You can put common shared properties in application.properties. Take a look at this https://stackoverflow.com/a/55933568/320087 – Niraj Sonawane May 22 '19 at 03:15
  • That's what I did. I have in Git common properties across services for specific env (application-env.yml), and common properties across services and across env (application.yml). Was just saying that Ithought I could keep in the code the PropertySource annotation while using Spring Cloud Config. But seems that it is not possible. – Mykeul May 22 '19 at 07:39
  • Last thing is how to externalize spring.profiles.include but this is another question https://stackoverflow.com/questions/56163411/spring-profiles-include-property-from-spring-cloud-config – Mykeul May 23 '19 at 07:10