使用spring-web 和 不是用spring-web各自的最小依赖
web 和非web使用spring各自的最小依赖
@Value加载属性的范围包括:
在纯 Spring 项目中,@Value
注解会从以下来源加载配置项:
(1) Java 系统属性
- Spring 会从 JVM 的系统属性中查找配置项。
- 示例:如果通过
-Dproperty.key=value
设置了系统属性,则@Value("${property.key}")
会获取到该值。
(2) 环境变量
- Spring 会从操作系统的环境变量中查找配置项。
- 示例:如果设置了环境变量
PROPERTY_KEY=value
,则@Value("${property.key}")
可能会匹配到该值(具体取决于你的命名约定)。
(3) PropertyPlaceholderConfigurer 或 PropertySourcesPlaceholderConfigurer
- 如果你在 Spring 配置中显式地定义了
PropertyPlaceholderConfigurer
或PropertySourcesPlaceholderConfigurer
,那么@Value
注解会从这些配置器加载的属性文件中读取值。 - 示例:
在这种情况下,<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config.properties</value> </list> </property> </bean>
@Value("${property.key}")
会从config.properties
文件中读取值。
(4) 自定义的 PropertySource
- 如果你在 Spring 应用上下文中手动添加了自定义的
PropertySource
,那么@Value
注解会从这些来源中读取值。 - 示例:
@Bean public static PropertySource<?> customPropertySource() { Map<String, Object> properties = new HashMap<>(); properties.put("property.key", "customValue"); return new MapPropertySource("customProperties", properties); }
(5) 默认值
- 如果上述所有地方都未找到配置项,则会使用
@Value
注解中指定的默认值。 - 示例:
${property.key:defaultValue}
中的defaultValue
会在找不到property.key
时被使用。
在非web的 Spring 项目中,通常通过以下方式加载配置文件:
(1) 使用 XML 配置
- 如果你使用的是基于 XML 的配置,可以通过
<context:property-placeholder>
或PropertyPlaceholderConfigurer
加载属性文件。 - 示例:
这样,<context:property-placeholder location="classpath:config.properties"/>
@Value("${property.key}")
会从config.properties
文件中读取值。
(2) 使用 Java 配置
- 如果你使用的是基于 Java 的配置,可以通过
@PropertySource
注解加载属性文件。 - 示例:
在这种情况下,@Configuration @PropertySource("classpath:config.properties") public class AppConfig { // 配置内容 }
@Value("${property.key}")
会从config.properties
文件中读取值。
(3) 手动加载属性文件
- 你也可以通过代码手动加载属性文件,并将其注册到 Spring 上下文中。
- 示例:
@Bean public static PropertySourcesPlaceholderConfigurer propertyConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); Resource resource = new ClassPathResource("config.properties"); configurer.setLocation(resource); return configurer; }