英文:
PropertySource property file is being ignored by scanning env property file
问题
在我的Spring Boot项目中,我在资源文件夹直接放置了环境属性(application-dev.prop)文件,该属性文件中定义了一些连接属性。相同的连接属性在user.properties文件中以不同的值进行了定义(需要在特定的配置类中进行注入),该文件位于resources/config下。我已经在那个特定的配置类上加上了@PropertySource(value = "classpath:/config/user.properties")的注解。但是不管怎样,这个配置类始终从环境属性文件中获取连接值,而不是从user.prop文件中获取,即使该类已经用属性源user.property类路径进行了注解。只有当环境属性文件中没有定义特定字段时,该配置类才会接受user.property的值。简而言之,它仅在环境属性文件中未定义任何字段/属性时才会检查user.property文件。但是我希望这个配置类始终指向user.property文件。我已经检查了Spring Boot扫描属性文件的优先级,但是无法解决。有谁可以帮助我解决这个问题。
英文:
In my spring boot project, I have env property(application-dev.prop) file placed directly under resources folder, this prop file has some connection properties defined. The same connection properties with different value defined in user.properties file( which needs to be injected in a specific config class)placed under resources/config.I have annotated that specific config class with @PropertySource(value = "classpath:/config/user.properties"). But however this config class takes connection values from env property file but not from user.prop file even if that class annotated with property source user.property class path. This config class only accepts user.property value if a particular field not defined in env property file. In short it checks user.property file only if any field/property not defined in env.property file. But I want this config class to point user.property file always. I already checked spring boot precedence for scanning property file but couldn't resolve. Can anyone help me fix this issue.
答案1
得分: 0
根据文档,
在某些情况下,如果一个给定的属性键存在于多个 .properties 文件中,
最后处理的 @PropertySource 注解将会“获胜”并进行覆盖。
我认为一个更好的方法是,如果适用的话,可以使用配置文件(profile)来处理。链接这里很清楚地解释了如何添加配置文件(profile)。你可以查看一下。
另一种方法是,如果你认为添加配置文件(profile)不是正确的选择,你可以将它们作为环境变量传递下来。这样可以灵活地根据需要进行更改,你还可以为环境变量设置默认值。
英文:
As per the doc,
In cases where a given property key exists in more than one .properties file,
the last @PropertySource annotation processed will 'win' and override.
I think a better approach would be to use a profile if that fits your use case.
The link here explains how to add profiles pretty neatly. you can check tht out.
Another approach I would suggest if you think adding a profile is not the right choice, you can make them passed down as environment variables. This gives you flexibility to change it as necessary and you can also give a default value for the environment variables.
专注分享java语言的经验与见解,让所有开发者获益!
评论