springboot对resource目录下配置文件读取和修改

本文介绍如何在Java中通过Spring Boot框架读取配置文件的属性,并应用于对象实例化及定时任务的配置。详细解释了使用@Component、@Data、@PropertySource和@ConfigurationProperties等注解来读取配置文件,以及通过ClassLoader读取和修改配置文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 将配置文件中的key作为对象的属性进行读取

     test.properties进行读取

   创建一个类对应配置文件中的key

@Component
@Data
@PropertySource("test.properties")
@ConfigurationProperties(prefix="obj")
public class ObjectProperties {
    private String name;
    private int age;
}

@Data注解添加可以不用在写get/set方法

在controller中使用配置文件中的配置信息

@Autowired
private ObjectProperties objectProperties;    
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test() throws Exception {
    return "name : " + objectProperties.getName() + " age : " + objectProperties.getAge();
}

 

2. 通过流的方式对test.properties进行修改,读取

    读取:

/**
 * @Title: getProfileByClassLoader
 * @Description: 采用ClassLoader(类加载器)方式进行读取配置信息
 * @return Map<String,Object> 以Map键值对方式返回配置文件内容
 * @param fileName 配置文件名称
 * 优点:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
 * 缺点:只能加载类classes下面的资源文件
 */
public static Map<String, Object> getProfileByClassLoader(String fileName) {
    // 通过ClassLoader获取到文件输入流对象
    InputStream in = Profile.class.getClassLoader().getResourceAsStream(fileName);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    Properties props = new Properties();
    Map<String, Object> profileMap = new HashMap<String, Object>();
    try {
        props.load(reader);
        for (Object key : props.keySet()) {
            profileMap.put(key.toString(), props.getProperty(key.toString()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return profileMap;
}

   修改:

/**
 * 传递键值对的Map,更新properties文件
 * @param fileName 文件名(放在resource源包目录下),需要后缀
 * @param keyValueMap 键值对Map
 */
public static void updateProperties(String fileName, Map<String, String> keyValueMap) throws Exception {
    //获取文件路径
    String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();
    System.out.println("propertiesPath:" + filePath);
    Properties props = new Properties();
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // 从输入流中读取属性列表(键和元素对)
        br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
        props.load(br);
        br.close();
        // 写入属性文件
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
        // 清空旧的文件
        // props.clear();
        for (String key : keyValueMap.keySet()) {
            props.setProperty(key, keyValueMap.get(key));
        }
        props.store(bw, "改变数据");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Visit " + filePath + " for updating " + "" + " value error");
    } finally {
        try {
            br.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3 定时任务的定时表达式从配置文件中读取

    3.1  在类前面添加   @PropertySource("classpath:test.properties")

    3.2 在定时执行方法签添加   @Scheduled(cron = "${cron.expression}")  使用@Scheduled注解的方法  参数应该设置为空                  @Scheduled(cron = "${cron.expression}")

            public String ScheduledMethod(){}
    3.3 在test.properties中添加

cron.expression=* */2 * * * ?

 

 

 

### Spring Boot 获取 `resources` 目录配置文件路径的方法 在 Spring Boot 项目中,有多种方式可以获取位于 `resources` 目录下的配置文件路径。以下是几种常见且有效的方法: #### 方法一:使用 `getResource()` `toURI()` 对于简单的场景,可以直接利用 Java 的内置功能来访问资源文件并转换成 URI 形式的路径。 ```java public String getConfigFilePathViaResourceToUri() { URL url = getClass().getClassLoader().getResource("application.properties"); Path path; try { path = Paths.get(url.toURI()); return path.toString(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } ``` 这种方法适用于开发环境,在打包后的 JAR 文件内可能不适用,因为它依赖于物理文件系统的存在[^1]。 #### 方法二:使用 `ClassPathResource` 类 借助 Spring 提供的工具类 `ClassPathResource` 可以更方便地处理这种情况,尤其适合运行时从 classpath 加载资源的情况。 ```java import org.springframework.core.io.ClassPathResource; public String getConfigFilePathFromClassPathResource() throws IOException { ClassPathResource resource = new ClassPathResource("application.properties"); File file = resource.getFile(); // 如果是在JAR包内部,则会抛出异常 return file.getAbsolutePath(); } ``` 需要注意的是,当应用程序被打包为 JAR 或 WAR 文件部署时,此方法可能会失败,因为在这些情况下,资源通常不会作为独立文件存在于磁盘上[^2]。 #### 方法三:使用 `ResourceUtils` 工具类 Spring 还提供了另一个实用程序类叫做 `ResourceUtils`,它能够帮助定位 classpath 下面的资源位置。 ```java import org.springframework.util.ResourceUtils; public String getConfigFilePathFromResourceUtils() throws FileNotFoundException { File file = ResourceUtils.getFile("classpath:application.properties"); return file.getPath(); } ``` 同样地,如果应用是以 JAR/WAR 格式发布的,那么上述代码将会遇到问题,因为此时找不到对应的实体文件[^5]。 为了确保无论在哪种环境下都能稳定工作,推荐采用基于输入流的方式来读取配置内容而不是尝试获得其绝对路径。例如,可以通过 `InputStreamReader` 结合 `BufferedReader` 来逐行解析配置项;或者直接调用 `Properties.load(InputStream)` 将整个属性集加载到内存中进行后续操作。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值