Spring如何知道获取用@value注释的变量值时要引用哪个属性文件?
如果我们的应用程序中有多个属性文件,并且这两个文件都设置了具有不同值的变量,该怎么办 我们通常只注入如下所示的值,它总是设法从属性文件中获取值。怎么做Spring如何知道获取用@value注释的变量值时要引用哪个属性文件?,spring,spring-boot,Spring,Spring Boot,如果我们的应用程序中有多个属性文件,并且这两个文件都设置了具有不同值的变量,该怎么办 我们通常只注入如下所示的值,它总是设法从属性文件中获取值。怎么做 @Configuration public class AppConfig { @Value("${spring.datasource.url}") private String datasourceUrl; Spring读取的最后一个文件中的值将覆盖以前读取的所有值。如果您自己定义文件的读取顺序(例如通过配置),那么您
@Configuration
public class AppConfig {
@Value("${spring.datasource.url}")
private String datasourceUrl;
Spring读取的最后一个文件中的值将覆盖以前读取的所有值。如果您自己定义文件的读取顺序(例如通过配置),那么您就可以完全控制它。请看以下示例: 基于注释的配置:
@Configuration
@PropertySource({"classpath:foo.properties", "classpath:bar.properties"})
public class PropertiesWithJavaConfig {
//...
}
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
基于XML的配置:
@Configuration
@PropertySource({"classpath:foo.properties", "classpath:bar.properties"})
public class PropertiesWithJavaConfig {
//...
}
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
如果
bar.properties
包含也在foo.properties
中定义的属性,则bar.properties
中的值将覆盖foo.properties中的值,Spring读取的最后一个文件中的值将覆盖以前读取的所有值。如果您自己定义文件的读取顺序(例如通过配置),那么您就可以完全控制它。请看以下示例:
基于注释的配置:
@Configuration
@PropertySource({"classpath:foo.properties", "classpath:bar.properties"})
public class PropertiesWithJavaConfig {
//...
}
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
基于XML的配置:
@Configuration
@PropertySource({"classpath:foo.properties", "classpath:bar.properties"})
public class PropertiesWithJavaConfig {
//...
}
<context:property-placeholder location="classpath:foo.properties,classpath:bar.properties"/>
如果bar.properties
包含也在foo.properties
中定义的属性,则bar.properties
中的值将覆盖foo.properties中的值
当涉及到属性文件时,它会检查application.properties
,然后检查application-.properties
,其中
由spring.profiles.active
环境变量设置(对于*.yaml
文件也是如此)
它将按此优先级在以下目录中搜索应用上述规则的属性文件:
(列表中较高的位置覆盖从较低位置加载的属性)
- 当前目录的
/config
子目录
- 当前
/
目录
- 类路径的
/config
包(如果使用maven,则src/main/resources/config中的所有内容)
- 类路径的根
/
(如果使用maven,则src/main/resources
中的所有内容)
弹簧靴
当涉及到属性文件时,它会检查application.properties
,然后检查application-.properties
,其中
由spring.profiles.active
环境变量设置(对于*.yaml
文件也是如此)
它将按此优先级在以下目录中搜索应用上述规则的属性文件:
(列表中较高的位置覆盖从较低位置加载的属性)
- 当前目录的
/config
子目录
- 当前
/
目录
- 类路径的
/config
包(如果使用maven,则src/main/resources/config中的所有内容)
- 类路径的根
/
(如果使用maven,则src/main/resources
中的所有内容)
nice explanationSpring Boot实际上使用的不仅仅是application.properties
文件。您可以在本文档中看到:当然,问题只是关于属性文件。。。我将添加关于所有属性源的一般性讨论尼斯解释Spring Boot实际上使用的不仅仅是application.properties
文件。您可以在本文档中看到:当然,问题只是关于属性文件。。。我将添加关于所有财产来源的一般性讨论。您应该查看本文档:您应该查看本文档: