YML配置文件 及让springboot启动时加载我们自定义的yml配置文件的几种方式
warning:
这篇文章距离上次修改已过416天,其中的内容可能已经有所变动。
在Spring Boot中,您可以通过以下几种方式加载自定义的YML配置文件:
- 使用
@PropertySource注解加载YML配置文件。
@Configuration
@PropertySource("classpath:myconfig.yml")
public class MyConfiguration {
// ...
}注意:@PropertySource仅支持properties文件,不支持YML。
- 使用
@ConfigurationProperties注解绑定YML配置。
@Configuration
@ConfigurationProperties(prefix = "my")
@PropertySource("classpath:myconfig.yml")
public class MyConfiguration {
// ...
}- 使用
@ImportResource注解加载Spring的XML配置文件,在XML文件中引入YML资源。
@Configuration
@ImportResource("classpath:application-context.xml")
public class MyConfiguration {
// ...
}在application-context.xml中:
<bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
<property name="resources" value="classpath:myconfig.yml" />
</bean>
<context:property-placeholder properties-ref="yamlProperties" />- 在
application.yml中引入自定义配置文件。
spring:
profiles:
include: myconfig然后在myconfig.yml中定义配置。
- 使用Spring Boot的
@ActiveProfiles注解或通过命令行参数来激活配置文件。
@SpringBootTest
@ActiveProfiles("test")
public class MyTests {
// ...
}或者在运行应用时:
$ java -jar yourapp.jar --spring.profiles.active=myconfig- 使用
@ConfigurationProperties绑定YML配置,并将配置文件放置在特定目录下。
@ConfigurationProperties(prefix = "my")
@EnableConfigurationProperties
public class MyProperties {
// ...
}然后在src/main/resources/config/myconfig.yml中定义配置。
- 使用Spring Cloud Config Server来加载配置。
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
// ...
}然后配置服务器将加载Git仓库中的YML配置文件。
以上方法可以根据实际需求选择使用,但最常用的是通过application.yml来引入自定义配置文件。
评论已关闭