How to make properties file in Spring boot Primary and secondary - spring

Hi I am using Spring 4.3.7, java 8 and spring boot, My requirement is I have 2 properties file one inside the classpath and another outside. I was able to load both. using
#PropertySources({ #PropertySource("classpath:common.properties"), #PropertySource("classpath:anotherFile.properties") })
#PropertySource(value = {"file:${external.config.location}/config_one.properties"}, ignoreResourceNotFound = true)
the input values of both the file will be almost same eg file naming convention or file create location (besides db details and few other token details)
what has to be done is if external property file exist read the property value from it or else read from one inside the classpath. is this possible via any annotation in Spring boot?

It works out of the box. The difference is that it does not "alternatively" read prop from one or another source, but it rather reads all properties from the first source, then reads all properties from another (and overrides eventual duplicates), than moves to the third source... and so on and on
There are in total 17 "default" sources and all have its own precedence over the others. See more in docs
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
Please bare in mind, that those sources are read "from bottom to top", so eg key from internal application.properties #15 will be overriden by key from external appication.properties #14 and so on.

Related

Spring boot Load all files based on pattern and place it in HashMap

I am developing an app where there will be a properties file for each type of database.
I want to load the properties file corresponding to the database based on the driver available in classpath using spring boot custom auto configuration and put it in a common holder object as a map.
For example, lets say I have oracle driver on classpath, So i need to load oracle-metadata.properties and place it in map with key as "oracle" and value as the properties object.
Current Approach
#ConfigurationProperties
#PropertySource("classpath:oracle-metadata.properties")
public class OracleMetadataConfiguration{
//if i have the object attributes corresponding to properties file, i will end up having duplicate attributes for each type of database
}
Application.properties
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.**.autoconfiguration.OracleMetadataConfiguration
How do i use the different instance representation for same configuration object structure?
What is the best way to design this?

Spring boot yaml property binding: collection types

I find Spring Boot's (or spring in general) handling of yaml collections to be a bit peculiar. Collections according to yaml specs should be written in .yaml files as:
myCollection: ['foo', 'bar']
or
myCollection:
- foo
- bar
But neither #Value("${myCollection}") annotation or Environment.getProperty("myCollection", String[].class) (also tried List.class) can read collection properties (returns null). The only method I know of that works is to use #ConfigurationProperties annotation described in spring boot docs.
The problem with #ConfigurationProperties annotation is that (a) it is too verbose if all I want is a single property and (b) it rely on bean injection to get an instance of the #ConfigurationProperties class. Under some circumstances, bean injection is not available and all we have is a reference to Environment (e.g: thru ApplicationContext).
In my particular case, I want to read some properties during ApplicationEnvironmentPreparedEvent event, since it happens before context is built, the listener has to be manually registered and therefore, no bean injection. Via the event argument, I can get a reference to Environment. So, I can read other properties but cannot read collections.
A couple of "solutions" I noted (quoted because I don't find them very satisfactory):
Specify collections in .yaml file as myCollection: foo, bar. But this is not ideal because, the format isn't really yaml anymore.
Read individual elements using an index, for example Environment.getProperty("myCollection[0]", String.class). Will require some not-so-elegant utility methods to read and put all elements into a List.
So, my questions is - What is a good way to read collection-type properties if I cannot use #ConfigurationProperties? Also curious why comma-separated format works but not yaml-style collections.
EDIT: corrected some typos
Quite Frankly Spring boot application.properties and application.yaml or application.yml is meant to load configuration properties.
The #ConfigurationProperties annotation is designed as an abstraction to hide the implementations of configuration properties and support both .properties and .yaml/.yml.
For yaml/yml however Spring uses org.yaml.snakeyaml.Yaml library underneath to parse the file and load it to a Properties object inside org.springframework.boot.env.YamlPropertySourceLoader and a Collection is mapped as a Set not an array or List. So you try doing the following;
Environment.getProperty("myCollection", Set.class)

Confige place holder in properties file with Java Code - Spring Boot

I have properties file in Spring Boot application , with end points mentioned as below :-
user.details = /api/{userID}/get-user
I am using POJO with #PropertySource, #Configuration to read values.
Now my requirement is to replace the userID value dynamically from the java code after reading it from properties file, when I receive the ID from front end application. I will not pass this value from command line as it does not serve my use case.

Read properties file in original order from Spring Application Context

I need to read original order properties file from Spring Application context.
example:
A.properties
1:abc
2:xyz
3:qwe
The above file I need to get in the same order.

How can I explicitly define an order in which Spring's out-of-the-box process of reading properties out of an available-in-classpath application.yml

UPDATE: I just published this question also here, I might have done a better work phrasing it there.
How can I explicitly define an order in which Spring's out-of-the-box process of reading properties out of an available-in-classpath application.yml will take place BEFORE my #Configuration annotated class which reads configuration data from zookeeper and places them as system properties which are later easily read and injected into members using #Value?
I have a #Configuration class, which defines a creation of a #Bean, in a which configuration data from zookeeper is read and placed as system properties, in a way that they can easily be read and injected into members using #Value.
#Profile("prod")
#Configuration
public class ZookeeperConfigurationReader {
#Value("${zookeeper.url}")
static String zkUrl;
#Bean
public static PropertySourcesPlaceholderConfigurer zkPropertySourcesPlaceHolderConfigurer() {
PropertySourcesConfigurerAdapter propertiesAdapter = new PropertySourcesConfigurerAdapter();
new ConfigurationBuilder().populateAdapterWithDataFromZk(propertiesAdapter);
return propertiesAdapter.getConfigurer();
}
public void populateAdapterWithDataFromZk(ConfigurerAdapter ca) {
...
}
}
Right now I pass the zookeeper.url into the executed program using a -Dzookeeper.url which is added to the execution line. Right now I read it by calling directly System.getProperty("zookeeper.url").
Since I'm using Spring-Boot application, I also have a application.yml configuration file.
I would like to be able to set the zookeeper.url in the application.yml, and keep my execution line clean as possible from explicit properties.
The mission turns out to be harder than I thought.
As you can see in the above code sniplet of ZookeeperConfigurationReader, I'm trying to inject that value using #Value("${zookeeper.url}") into a member in the class which performs the actual read of data from zookeeper, but at the time the code that needs that value accesses it, it is still null. The reason for that is that in spring life cycle wise, I'm still in the phase of "configuration" as I'm a #Configuration annotated class myself, and the spring's code which reads the application.yml data and places them as system properties, hasn't been executed yet.
So bottom line, what I'm looking for is a way to control the order and tell spring to first read application.yml into system properties, and then load ZookeeperConfigurationReader class.
You can try to use Spring Cloud Zookeeper. I posted a brief example of use here

Resources