spring怎么加载外部配置文件

1106
2023/10/10 1:36:31
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

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

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

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

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

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: spring事务管理的方式有哪些