Home > Mobile >  SpringBoot 2.7.5 - @Value annotation not assigning any values from application.properties file
SpringBoot 2.7.5 - @Value annotation not assigning any values from application.properties file

Time:12-14

I am using Spring Boot 2.7.5 While using @Value annotation to inject values form application.properties file, getting null assignment to variables under @Configuration class.

Example:

@Value("${file.name}")
private String fileName;

Here I am getting seeing assignment to variable fileName Ideally it should assign value '${file.name}' if key isn't matching. But null assignment means something is breaking in the project (at least I think so, I need experts comments on this).

Same thing is working in another project but not in this particular.

Let me know if my question is not elaborative enough and will try to explain in detail

My question is, why is it working in other project but not in this one. What configurations could go wrong which I need to check. Have gone through multiple stackoverflow solutions and verified all below:

  1. application.properties file spell check
  2. @Configuration annotation at top of class where @Value is being used
  3. key value pair assignment and spell check of all keys
  4. no issues with library imports
  5. Tried to add @PropertySource("classpath:foo.properties")
  6. import org.springframework.beans.factory.annotation.Value;
  7. resources folder is correctly marked as 'Resources Root'

Temporary Alternative

private Properties props = new Properties();
props.load(VaultCredential.class.getResourceAsStream("/application.properties"));
props.getProperty("file.name");

CodePudding user response:

Can you please try with below code

private String PathForImageGallery;

@Value("${file.name}")
public void PathForImageGallery(String PathForImageGallery) {
    this.PathForImageGallery = PathForImageGallery;
}

CodePudding user response:

Apologies everyone. I was calling a class where was trying to bind @Value with properties and calling it in main() method of @SpringBootApplication. Totally missed that main() method will not load property values until spring application is up and running.

Working solution if some one want to load properties before even running a SpringBoot application -

private Properties props = new Properties();
props.load(VaultCredential.class.getResourceAsStream("/application.properties"));
props.getProperty("file.name");

PS - Thanks all for your efforts. Admins can close it down if considered as non-logical question.

  • Related