springboot项目读取自定义properties文件

参考:https://blog.csdn.net/thc1987/article/details/78789426

根据连接中的四种读取springboot项目中的文件(前三种是读取application.properties,第四种是读取自定义properties文件),我是用第四种任然无法读取成功,所以我用到了下面这种方法:

springBoot基础系列--properties配置https://www.cnblogs.com/V1haoge/p/7183408.html

简单说明一下,在项目中使用到图片上传功能,所以想在自定义的配置文件中配置上传的文件的参数,包括上传图片存储路径以及图片最大size等

1:测试配置文件TestConfig.java

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Auther: JohnDoeo
 * @Date: 2018/12/20 21:16
 * @Description:
 */
@Configuration
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix="test")
public class TestConfig {
    private String path;

    public void setPath(String path){this.path=path;}

    public String getPath(){return path;}
}

2:自定义配置文件test.properties

test.path=thisIsATestFile

3:在要使用该自定义配置文件的控制器类上加上@EnableConfigurationProperties(TestConfig.class)注解,并且在该控制器类中添加以下属性就可以在该控制器中使用配置文件中配置的数据了

    @Value("${test.path}")
    private String pathStr;

以下是完整的测试控制器类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
@EnableConfigurationProperties(TestConfig.class)
public class TestController {
    
   
    @Value("${test.path}")
    private String pathStr;

    @RequestMapping(value = "/tset",method = {RequestMethod.POST})
    public String test(){
        System.err.println(pathStr);
        return pathStr;
    }
}

4:好了,接下来启动springboot项目访问http://localhost:8080/demo/tset.do,后台就会有如下输出(或者前台可以直接返回字符串)

完美,洗洗睡吧!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值