租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

spring怎么加载外部配置文件,spring是如何加载配置的

发布时间:2023-09-19 07:45:41

spring怎样加载外部配置文件

在Spring中,可使用`PropertyPlaceholderConfigurer`或`PropertySourcesPlaceholderConfigurer`来加载外部配置文件。
1. 使用`PropertyPlaceholderConfigurer`加载外部配置文件:
```xml



```
其中,`config.properties`是外部配置文件的路径。
2. 使用`PropertySourcesPlaceholderConfigurer`加载外部配置文件:
```java
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
// ...
}
```
在这类方式下,需要在Spring的Java配置类上使用`@PropertySource`注解,并指定外部配置文件的路径。
在两种方式下,外部配置文件中的属性可以通过`@Value`注解或`Environment`对象进行注入和访问。
```java
@Value("${property.key}")
private String propertyValue;
@Autowired
private Environment env;
public void someMethod() {
String propertyValue = env.getProperty("property.key");
}
```