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

时间:2019-06-05 02:10:16

标签: java spring spring-boot

我正在尝试设置application.properties的值,我需要在此处设置文件的路径。

我知道我可以做到:

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

但是我从方法中获得了价值,所以我正在尝试类似的事情

@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;
}

这是行不通的,我想这不是我正在做的理想方式,有什么想法吗?预先感谢

1 个答案:

答案 0 :(得分:1)

请看下面的例子。您可以在类中应用@Value注释以自动进行连接。请确保将getter和setter写入绝对路径变量,而不是通过赋值运算符分配值。然后使用get方法将其返回给应用程序。

  1. 数据类

     @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. 通过方法返回值

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


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

            return data.getAbsolutePath();

        }

    }
  1. Application.properties文件
    catalog.path:theValuePath="src/test/resources/MyFile.xml"
相关问题