Spring Boot外部化属性不起作用

时间:2016-04-14 22:32:13

标签: java spring tomcat properties spring-boot

我查看了下面的主题并按照那里给出的内容。仍然没有发生我的财产覆盖

1)Spring Boot - Externalized properties
2)Profile Specific Property Enablement
3)Spring Boot External Config

我在tomcat 8.0.33和Spring boot starter web上,并在我的setenv.sh中得到了这个

export JAVA_OPTS="$JAVA_OPTS -Dlog.level=INFO -Dspring.config.location=file:/opt/jboss/apache-tomcat-8.0.33/overrides/ -Dspring.profiles.active=dev"

在覆盖文件夹中,我有2个文件

1)application.properties 2)application-dev.properties

application.properties中只有一个条目

spring.profiles.active=dev

我看到正确的log.level被提供给我的代码,这意味着这个命令正在运行。只是因为我为什么覆盖不按预期发生而无能为力

我的工作区中没有任何`PropertyPlaceholderConfigurer代码。我甚至不确定我是否需要1

请帮助!!!

1 个答案:

答案 0 :(得分:3)

我没有使用此方法来外部化属性。首先,我会尝试为您的方法提出建议,然后我会向您展示我正在使用的内容。

你的方法的建议是使用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中,Spring将加载DevelopmentConfig类中定义的所有属性和Bean以及ApplicationConfig中的所有属性和Bean。如果我传递" prod",则会加载ProductionConfig和ApplicationConfig属性。

我正在完成有关如何使用安全性,电子邮件,数据JPA,Amazon Web Services,Stripe等创建Spring Boot网站的课程。如果您愿意,可以注册您的兴趣here,当课程开放供您注册时,您会收到通知。

相关问题