Springboot 读取resources目录下文件或者自定义文件的方式

想读取resouce/xxxx 目录下的yyy文件。只有第二种方式才能正常工作!

第一种方式( 这种方法在linux下无法工作):
File sourceFile = ResourceUtils.getFile(“classpath:picture/bottom.png”);
第二种方式:
Resource resource = new ClassPathResource(“picture/bottom.png”);
// 有些系统提示找不到资源,可以把上面的代码换成下面这句:
// ClassPathResource resource = new ClassPathResource(“picture/bottom.png”);
File sourceFile = resource.getFile();

 //获取文件
ClassPathResource resource = new ClassPathResource("xxxx/rrrrr.csv");
File sourceFile = resource.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用YAML(YAML Ain't Markup Language)文件来进行配置。常见的YAML文件名为application.yml或application.yaml。 为了实现自定义的YAML文件读取,可以按照以下步骤操作: 1. 在src/main/resources目录下创建一个新的YAML文件,例如custom.yml,用于存放自定义的配置项。 2. 在Spring Boot的配置类中,使用@ConfigurationProperties注解,并指定prefix属性为自定义的配置项前缀。 例如,如果自定义的配置项前缀为custom,可以将配置类的注解写成如下形式: ```java @Configuration @ConfigurationProperties(prefix = "custom") public class CustomConfig { private String name; private int age; // 其他属性及对应的getter和setter方法 } ``` 3. 在类中定义相应的属性,并为每个属性编写getter和setter方法。 4. 在配置类所在的包中创建一个名为CustomConfigurator的类,用于在启动时将自定义配置加载到Spring容器中。 ```java @Component public class CustomConfigurator implements CommandLineRunner { @Autowired private CustomConfig customConfig; @Override public void run(String... args) { // 在Spring启动时执行的逻辑 // 可以在这个方法中获取和使用自定义配置项 String name = customConfig.getName(); int age = customConfig.getAge(); // 其他逻辑 } } ``` 5. 在application.yml中添加以下内容,指定自定义配置文件的路径: ```yaml spring: profiles: include: custom ``` 这样,Spring Boot会加载application.yml以及custom.yml中的配置,并将其注入到CustomConfig配置类对应的属性中。 通过以上步骤,就实现了自定义的YAML文件读取。在启动应用时,Spring Boot会自动加载并注入自定义配置项,可以在代码中直接使用。 需要注意的是,自定义配置项的前缀要与custom.yml文件中的层级结构对应,而且类名和属性名要与custom.yml文件中的字段名保持一致。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值