Search code examples
springspring-boot

@Value not found from application.properties in main @SpringBootApplication class


I created a new Spring Boot project which came with an application.properties

spring.application.name=demo

Per these instructions I added AppConfig.java

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig { }

The main @SpringBootApplication class is trying to read this variable and it's NULL. (I also tried making it a @Component thinking that @Value may depend on it but it didn't work.)

@SpringBootApplication
@Component // added to potentially help find @Value, didn't work
public class DemoApplication {

    @Value("spring.application.name")
    static String appName;
    
    public static void main(String[] args) {
        System.out.println("name: " + appName);
        SpringApplication.run(DemoApplication.class, args);
    }

}

The value is NULL and it's not found. The structure is

   /demo
      /src
        /main
          /java.com.example.demo
              AppConfig.java  (added)
              DemoApplication.java
          /resources
              application.properties (existing)

I have the POM dependency

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

What am I missing?


Solution

  • This was the answer: https://stackoverflow.com/a/74026849/1005607

    We can't read it in main because we're constructing a new instance of the Application in main. If not inside a Service or Component, it was suggested to read it in a @PostConstruct method. Also, the variable cannot be static -- must be a normal private. This works inside the @PostConstruct method in this class, but not in main:

    @SpringBootApplication
    public class DemoApplication {
    
       @Value("spring.application.name")
       private String appName;
    
        public static void main(String[] args) {
           SpringApplication.run(DemoApplication.class, args);
        }
    
        @PostConstruct
        public void printCategory(){
            System.out.println("appName: " + appName);
        }
    
    }