Edward Muldrew
Edward Muldrew

Reputation: 273

Springboot application.properties file not working to use default & custom properties

So I have followed almost all tutorials/examples and stack overflow questions but I still can't seem to get my application.properties file to be able to fill in values in an ExternalConfig class I have created.

My application properties class file is located in src/main/resources and looks like this

app.developerName = "f21ad267-e241-4ed0-8943-721fa90bcf3a"
spring.boot.config.developerName = "f21ad267-e241-4ed0-8943-721fa90bcf3a"
server.port=9000
Access-Control-Allow-Origin: *

My purpose built External Config class looks like this

@ConfigurationProperties(prefix="spring.boot.config")
@Component
public class ExternalConfig {

private String developerName;

public String getDeveloperName() {
    return developerName;
}

public void setDeveloperName(String developerName) {
    this.developerName = developerName;
}   
}

Finally my Springboot main class looks like this

@EnableConfigurationProperties(ExternalConfig.class)
@SpringBootApplication
public class SpringBootMain implements CommandLineRunner {

@Autowired
ExternalConfig externalConfig;

@Bean
ResourceConfig resourceConfig() {
    return new ResourceConfig().registerClasses(ExternalConfig.class, Version1Api.class, Paypal.class);
}

public static void main(String[] args) {
    SpringApplication.run(SpringBootMain.class);
}

@Override
public void run(String... args) throws Exception {
    // TODO Auto-generated method stub
    System.out.println(externalConfig.getDeveloperName());

}  
}

Every time I run the code or debug it, the ExternalClass and it's variables are always null.

I am running out of ideas and methods to try do this an alternative way. Am I missing something in my pom.xml?

Upvotes: 0

Views: 5626

Answers (2)

Gopinath
Gopinath

Reputation: 4957

These 2 changes may help:

  1. Remove the blank spaces next to '=' symbol in the application.properties file
  2. Remove the word 'prefix=' from the @ConfigurationProperties annotation.

More information:

A very good article with working code on extracting the application properties.

https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/

Upvotes: 1

Beppe C
Beppe C

Reputation: 13993

I think you should define the bean differently

@Configuration
@ConfigurationProperties(prefix="spring.boot.config")
public class ExternalConfig {

Upvotes: 0

Related Questions