spring怎么加载外部配置文件

   2025-02-21 3190
核心提示:在Spring中,可以使用PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer来加载外部配置文件。使用PropertyP

在Spring中,可以使用PropertyPlaceholderConfigurerPropertySourcesPlaceholderConfigurer来加载外部配置文件。

使用PropertyPlaceholderConfigurer加载外部配置文件:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="classpath:config.properties"/></bean>

其中,config.properties是外部配置文件的路径。

使用PropertySourcesPlaceholderConfigurer加载外部配置文件:
@Configuration@PropertySource("classpath:config.properties")public class AppConfig {// ...}

在这种方式下,需要在Spring的Java配置类上使用@PropertySource注解,并指定外部配置文件的路径。

在两种方式下,外部配置文件中的属性可以通过@Value注解或Environment对象进行注入和访问。

@Value("${property.key}")private String propertyValue;@Autowiredprivate Environment env;public void someMethod() {String propertyValue = env.getProperty("property.key");}

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言