我不使用此方法来外部化属性。首先,我将为您的方法提出建议,然后再向您展示我在使用什么。
您的方法建议是使用file:///而不是file:/,就像Spring一样,我发现在冒号后不传递三个斜杠时,它无法识别该属性。
我已经为您创建了一个示例项目,可在此处获得相关说明。
现在,我使用的方法。
我为每个配置文件定义一个配置文件,并将application.properties文件保留在src / main / resources下。
然后,在每个配置文件上使用@Profile和@PropertySource批注。
例如:
@Configuration@Profile("dev")@PropertySource("file:///${user.home}/.devopsbuddy/application-dev.properties")public class DevelopmentConfig {@Beanpublic EmailService emailService() { return new MockEmailService();}@Beanpublic 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 {@Beanpublic 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=devdefault.to.address=me@example.comtoken.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网站的课程。如果您愿意,可以在这里注册您的兴趣,当课程开放供您注册时,您会收到通知。



