SpringBoot 2.x 自定义 application.properties 参数配置

在按照 《精通 SpringMVC》 里的代码敲的时候,无脑生成 set/get 方法,坑了自己一把,生成的 set 方法参数成了 Resource 类型,怎么都无法转换成功。。。

  • 修改 application.properties 的内容
upload.pictures.uploadPath=file:./pictures # 这表示跟 src 同级目录
upload.pictures.anonymousPicture=classpath:/images/anonymous.png
  • 配置类代码,全靠 set 方法来绑定参数,注意 set 方法中参数类型
@ConfigurationProperties(prefix = "upload.pictures")
public class PictureUploadProperties {
    private Resource uploadPath;
    private Resource anonymousPicture;

    public Resource getUploadPath() {
        return uploadPath;
    }
    
    // 这里的参数 uploadPath 类型一定要注意啊,就是靠 set 来绑定参数的
    public void setUploadPath(String uploadPath) throws IOException {
        this.uploadPath = new DefaultResourceLoader().getResource(uploadPath);
        if (!this.uploadPath.getFile().isDirectory()) {
            throw new IOException("Directory " + uploadPath + " does not exist");
        }
    }

    public Resource getAnonymousPicture() {
        return anonymousPicture;
    }
    
    public void setAnonymousPicture(String anonymousPicture) throws IOException {
        this.anonymousPicture = new DefaultResourceLoader().getResource(anonymousPicture);
        if (!this.anonymousPicture.getFile().isFile()) {
            throw new IOException("File " + anonymousPicture + " does not exist");
        }
    }
}
  • Main 中开启参数配置
@SpringBootApplication
@EnableConfigurationProperties({PictureUploadProperties.class})
public class MasterSpringMvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(MasterSpringMvcApplication.class, args);
    }

}

https://lixi.fun/2019/05/04/spring-boot-ConfigurationProperties/

转载于:https://www.cnblogs.com/lixifun/p/10810296.html

你可能感兴趣的:(SpringBoot 2.x 自定义 application.properties 参数配置)