Home > Mobile >  @Value is Null while using @PostConstruct
@Value is Null while using @PostConstruct

Time:09-30

I am trying to load YML files from a config package, but whenever I use the @Value("${..}") annotation it is null during the @PostConstruct method causing a Null Pointer. I need the @PostConstruct to load all files at once.

  @Value("${my.property.name}")
  private String directoryPath;

  private Map<String, Map<String, List<String>>> entityFiles = new HashMap<>();
  private List<String> fieldsToEnrichByPE = new ArrayList<>();

  @PostConstruct
  public void getFieldsToEnrich() throws IOException {
    ClassLoader cl = this.getClass().getClassLoader();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource[] resources = resolver.getResources("classpath*:/"   DIRECTORY_PATH   "*.yml"); // RESOURCES IS NULL
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    for (Resource resource : resources) { // THROWS NULL POINTER BECAUSE RESOURCES NEVER GETS POPULATED, DIRECTORY PATH IS NOT GETTING INSTANTIATED
      File ymlFile = resource.getFile();
      entityFiles.put(ymlFile.getName().replace(".yml", ""), mapper.readValue(ymlFile, Map.class));
    }
  }

Any thoughts on how to alleviate this problem?

Hardcoding directoryPath worked, but if it is hardcoded I am unable to use my test configuration files, as directoryPath is hardcoded to the main resources folder not the test resources folder.

YML File:

my:
  property:
    name: a/b/c/

CodePudding user response:

Probably you wrote the YML path incorrectly.

Try writing the resolver.getResources("classpath*:/" DIRECTORY_PATH "*.yml"); line written directly, to check if the path you made is incorrect.

Maybe even the Java Build path isn't assigned to the correct directory where the YML is placed.

This is the res folder in one of my projects, which is in the Java Build Path

This is the res folder in one of my projects, which is in the Java Buil Path

Those are my guesses, and apologies if im incorrect.

Have a nice day!

CodePudding user response:

The class you are defining the property you are going to read from your properties should contain @Component for Spring to prepare the variable first before executing @PostContruct

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class TestProp {
    
    @Value("${my.prop.test}")
    private String prop;

    @PostConstruct
    public void postConstructMethod() {
    
    System.out.println("prop= "   prop);
    }
}

Eclipse sysout

  • Related