简体   繁体   中英

Set a value from a variable to one properties from the application.properties file

I'm trying to set a value of my application.properties , I need to set there the path of a file.

I know I can do this:

@Value("${catalog.path:theValuePath}")
private String absolutePath;

but I got the value from a method, so I was trying something like this

@Value("${catalog.path}")
private String absolutePath=setCatalogPath();

public String setCatalogPath () {
    File file = new File("src/test/resources/MyFile.xml");
    String absolutePath = file.getAbsolutePath();
    return absolutePath;
}

It's not working and I guess is not the ideal way what I'm doing, any ideas? thanks in advance

Please look at below example. You can apply the @Value annotation in class to be auto wired.Make sure to write getters and setters to the absolutePath variable instead of assigning a value through assignment operator.Then use the get method to get the value back for application.

  1. Data class

      @Component public class Data { @Value("${catalog.path:theValuePath}") private String absolutePath; public String getAbsolutePath() { return absolutePath; } public void setAbsolutePath(String absolutePath) { this.absolutePath = absolutePath; } 
  2. Returning the value through a method

    @RestController
    @RequestMapping("/")
    public class Mycon {


        @Autowired
        Data data;
        @GetMapping
        public String hello(ModelMap model) {

            return data.getAbsolutePath();

        }

    }
  1. Application.properties file
    catalog.path:theValuePath="src/test/resources/MyFile.xml"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM