1

I am reading a file path from spring properties file as shown below and that is mapped into a java class

#file path
file.path =/root/ms_data/file/

and it is mapped into java class like this

@Value("${file.path}")
    private String fileDataPath;

Please advise can I keep it as final I mean like this as shown below in which I kept fileDataPath as the final one

@Value("${file.path}")
private final String fileDataPath;
user1529641
  • 67
  • 2
  • 9
  • Why you need final ? may be you need static instead . – Eklavya Apr 20 '20 at 07:10
  • @AbinashGhosh spring and `static` does not go well together and I can't see a reason why it should be used here – Lino Apr 20 '20 at 07:21
  • @Lino may be this class for reading properties file, so using static help to use member statically from class , since object of this class may not use anywhere – Eklavya Apr 20 '20 at 07:27
  • @AbinashGhosh That is a rather bad use of spring then, you should always work with components and inject them where you need to, else you will have lots of unknown static dependencies to a class and testing will give you nightmares. See also [this question](https://softwareengineering.stackexchange.com/questions/364496/are-spring-beans-declared-as-static-a-poor-design-choice) – Lino Apr 20 '20 at 07:29

1 Answers1

6

You can use constructor injection for this:

public class YourClass {
    private final String fileDataPath;

    public YourClass(@Value("${file.path}") String fileDataPath) {
        this.fileDataPath = fileDataPath;
    }
}

For more on constructor injection, I suggest reading through the following questions, they go into a lot more detail than I ever could:

Lino
  • 19,604
  • 6
  • 47
  • 65