Spring Boot Externalizing properties not working

I don’t use this method to externalise properties. First, I’ll try a suggestion for your method and then I’ll show you what I’m using.

The suggestion for your method is to use file:/// instead of file:/ as with Spring I found that when not passing the three slashes after the colon it didn’t recognise the property.

I’ve created a sample project for you, available here with instructions.

Now for the method I use.

I define a Configuration file for each profile and I keep the application.properties file under src/main/resources.

Then I use the @Profile and @PropertySource annotations on each configuration file.

For example:

@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;
}
}

And

@Configuration
@Profile("prod")
@PropertySource("file:///${user.home}/.devopsbuddy/application-prod.properties")
public class ProductionConfig {

@Bean
public EmailService emailService() {
    return new SmtpEmailService();
}
}

I have also got a Configuration file that is valid for all profiles, which I call ApplicationConfig, as follows:

@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 {
}

My src/main/resources/application.properties file looks like the following:

spring.profiles.active=dev
[email protected]
token.expiration.length.minutes=120

Of course I could externalise the spring.profile.active property by passing it as a system property but for my case and for now it’s fine.

When running the application, if I pass the “dev” profile, Spring will load all properties and Beans defined in the DevelopmentConfig class plus all those in ApplicationConfig. If I pass “prod”, the ProductionConfig and ApplicationConfig properties will be loaded instead.

I’m completing a course on how to create a Spring Boot website with Security, Email, Data JPA, Amazon Web Services, Stripe and much more. If you want, you can register your interest here and you will get notified when the course is open for enrolment.

Leave a Comment