简体   繁体   English

将变量的值设置为application.properties文件中的一个属性

[英]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. 我试图设置我的application.properties的值,我需要在那里设置文件的路径。

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. 您可以在类中应用@Value注释以自动连接。确保将getter和setter写入绝对路径变量中,而不是通过赋值运算符分配值。然后使用get方法将值返回给应用程序。

  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 Application.properties文件
    catalog.path:theValuePath="src/test/resources/MyFile.xml"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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