3

I have an application.yaml file which specifies the service's name:

spring:
  application:
    name: "my-microservice"

Now, when I try to fetch it using @Value("spring.application.name") inside my code, I'm able to do that successfully.

But I'm also using a "dev" profile for which I created a separate application-dev.yaml, but I didn't specify the spring.application.name inside this yaml. Now, when I try to run my code, the @Value annotation gives me a null. I thought that the fields not specified by application-dev.yaml should be populated using application.yaml, but apparently this is not happening. Am I supposed to just copy every common field from the default to the dev's application file? Or is there any other way? Any help is appreciated, Thanks :)

2 Answers2

3
  1. You need to use Spring Expression Language which says we should write it as
    @Value("${spring.application.name}")
    private String appName;
  1. For Default value if key is not present in yaml/yml or properties file
    @Value("${spring.application.name: defaultValue}") 
    private String appName;
  1. The last way you can fetch value is using environment object
   @Autowired  
   private Environment environment;
       
   String appName = environment.get("spring.application.name");
0

Ok I figured out the problem. It is true that the default application.yaml properties are read by spring for all profiles (unless they have been overwritten by a profile's application file) But in my case, I was trying to use the @Value annotation on a static field.

  @Value("${spring.application.name}")
  private static String applicationName;

This caused the null exception in my code. Removing the static context from the field worked for me.