我不使用这种方法来外部化属性。首先,我会为你的方法尝试一个建议,然后我会告诉你我正在使用什么。
对您的方法的建议是使用 file:/// 而不是 file:/ 与 Spring 一样,我发现当不通过冒号后的三个斜杠时,它无法识别该属性。
我为您创建了一个示例项目,available here with instructions。
现在是我使用的方法。
我为每个配置文件定义了一个配置文件,并将 application.properties 文件保存在 src/main/resources 下。
然后我在每个配置文件上使用@Profile 和@PropertySource 注解。
例如:
@Configuration
@Profile("dev")
@PropertySource("file:///${user.home}/.devopsbuddy/application-dev.properties")
public class DevelopmentConfig {
@Bean
public EmailService emailService() {
return new MockEmailService();
}
@Bean
public ServletRegistrationBean h2ConsoleServletRegistration() {
ServletRegistrationBean bean = new ServletRegistrationBean(new WebServlet());
bean.addUrlMappings("/console/*");
return bean;
}
}
和
@Configuration
@Profile("prod")
@PropertySource("file:///${user.home}/.devopsbuddy/application-prod.properties")
public class ProductionConfig {
@Bean
public EmailService emailService() {
return new SmtpEmailService();
}
}
我还有一个对所有配置文件都有效的配置文件,我称之为ApplicationConfig,如下:
@Configuration
@EnableJpaRepositories(basePackages = "com.devopsbuddy.backend.persistence.repositories")
@EntityScan(basePackages = "com.devopsbuddy.backend.persistence.domain.backend")
@EnableTransactionManagement
@PropertySource("file:///${user.home}/.devopsbuddy/application-common.properties")
public class ApplicationConfig {
}
我的 src/main/resources/application.properties 文件如下所示:
spring.profiles.active=dev
default.to.address=me@example.com
token.expiration.length.minutes=120
当然,我可以通过将 spring.profile.active 属性作为系统属性传递来将其外部化,但对于我的情况,现在它很好。
在运行应用程序时,如果我传递“dev”配置文件,Spring 将加载 DevelopmentConfig 类中定义的所有属性和 Bean 以及 ApplicationConfig 中的所有属性和 Bean。如果我通过“prod”,则将改为加载 ProductionConfig 和 ApplicationConfig 属性。
我正在完成有关如何使用 Security、Email、Data JPA、Amazon Web Services、Stripe 等创建 Spring Boot 网站的课程。如果您愿意,您可以注册您的兴趣here,当课程开放注册时您会收到通知。