Search code examples
javaspringspring-mvcspring-4

Priority of Various Sources in PropertySources


Spring has introduced a new annotation @PropertySources for all classes marked as @Configuration since 4.0. It takes different @PropertySource as argument.

@PropertySources({
    @PropertySource("classpath:application.properties"), @PropertySource("file:/tmp/application.properties")})

What I am interested is knowing is the ordering in case of conflict in values for the same key present in multiple properties file. I have not seen any documentation related to this that specifies an ordering. I have tries it multiple times and found that the PropertySource mentioned later is overwriting the value present in PropertySource mentioned before. But, how to be sure?


Solution

  • The documentation of @PropertySources does not say anything about the case where the same property exists in more than one @PropertySource files.

    However, the documentation of @PropertySource states the following :

    In cases where a given property key exists in more than one .properties file, the last @PropertySource annotation processed will 'win' and override

    Since the @PropertySource declarations within @PropertySources are actually a table, then it is fairly safe to assume that the last declared @PropertySource overrides the previous ones. This is consistent with the tests I've done and with this blog post.

    However, as mentioned in the question, it is not indicated clearly in the documentation. So the behavior might "accidentally" change in the future.