load properties in spring
时间: 2023-11-28 13:49:44 浏览: 51
In Spring, you can load properties from a properties file using the `PropertySourcesPlaceholderConfigurer` bean. Here's an example configuration in XML:
```xml
<bean class="org.springframework.beans.factory.config.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
```
This will load the `config.properties` file from the classpath. You can also specify multiple locations by adding more `value` elements to the list.
If you're using Java configuration, you can use the `@PropertySource` annotation:
```java
@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
// ...
}
```
This will load the `config.properties` file from the classpath as well.
Once the properties are loaded, you can use them in your beans by using the `@Value` annotation:
```java
@Component
public class MyBean {
@Value("${my.property}")
private String myProperty;
// ...
}
```
This will inject the value of `my.property` from the properties file into the `myProperty` field of the `MyBean` class.
阅读全文