SpringBoot 读取配置文件.properties

本文详细介绍了SpringBoot如何读取配置文件,包括默认的application.properties文件和自定义的.properties文件的加载。当使用@PropertySource注解加载自定义配置时,提供了多种写法示例。此外,文章还讲解了使用@Value、@ConfigurationProperties和Environment读取配置的方式,以及一种通过类名静态获取配置的方法,特别指出该方法在不同SpringBoot版本中的有效性差异。

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

当前选择的SpringBoot的版本:

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.5.RELEASE</version>
      <relativePath />
</parent>

 

若新增的配置信息,写在application.properties,则不需要使用注解@PropertySource载入文件。

反之,若是自定义的properties文件,则需要手动载入,在配置类加注解@PropertySource来载入,例如:

 

自定义properties文件:(yml文件不支持注解@PropertySource)


在spring boot启动类或配置类加注解,可启动时载入自定义的配置文件(写法有多种)

@PropertySource("classpath:config/xxx.properties")

@PropertySource(value = "classpath:/a.properties")

@PropertySources(@PropertySource(value = "classpath:/service.properties"))

@PropertySources(@PropertySource(value = "classpath:/service.properties",ignoreResourceNotFound = true, encoding = "UTF-8"))

若同时载入多个文件

@PropertySource(value={"classpath:config/a.properties","classpath:config/b.properties"})

 

自定义如下:

 

service.properties


 

info.name=kikiname
info.age=12

 

配置类:


1、@Value注解方式读取

@Component
@PropertySource(value = "classpath:/service.properties")
public class ServerPropertiesTwo {

    @Value("${info.name}")
    private String name;

    @Value("${info.age}")
    private Integer age;

    public String getName() {
        return name;
    }
    public Integer getAge() {
        return age;
    }
}

 

 

2、@ConfigurationPropterties注解读取方式-批量注入到类变量


在application.properties 中配置以info为前缀的参数

在java代码中用@ConfigurationPropterties将以info为前缀的参数注入到当前变量中,需要用setXXX()方法

@Component
@PropertySource(value = "classpath:/service.properties")
@ConfigurationProperties(prefix = "info")
public class PropertiesConfigurationService {

    private String name;

    private Integer age;

   public String getName() { 
        return name;
    }
    public Integer getAge() { 
        return age;
    }
    public void setName(String name) { 
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

 

3、Environment读取方式


以上所有加载出来的配置都可以通过Environment注入获取到

import org.springframework.core.env.Environment;

@Autowired

private Environment env;

// 获取参数

String value = env.getProperty(String key);

package com.kiki.info.resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kiki.info.config.util.readproperties.PropertiesConfigurationService;
import com.kiki.info.config.util.readproperties.PropertiesStateReadService;
import com.kiki.info.config.util.readproperties.PropertiesValueService;
import com.kiki.info.util.business.CommonResponse;

/**
 * 读取配置文件的俩种方式
 *
 * @ClassName: MessageReource
 * @author kiki
 * @date 2018年10月8日
 * @version: V1.0
 */
@RestController
@RequestMapping("/message")
public class PropertiesResource {
    private static Logger logger = LoggerFactory
            .getLogger(PropertiesResource.class);

    @Autowired
    private Environment env;

    /**
     *
     * getinfo1 获取属性值方式不同
     *
     * @return 参数 CommonResponse 返回类型
     */
    @GetMapping("/getname")
    public CommonResponse getinfo1() {
        System.out.println(env.getProperty("info.name"));
        String value = propertiesValueService.getName();
        logger.info("@Value name:" + value);
        logger.info("@ConfigurationProperties name:"
                + propertiesConfigurationService.getName());
        logger.info("static @Value AGE:" + PropertiesStateReadService.AGE
                + " NAME:"
                + PropertiesStateReadService.NAME);
        return CommonResponse.getInstance(value);
    }

    @Autowired
    PropertiesValueService propertiesValueService;
    @Autowired
    PropertiesConfigurationService propertiesConfigurationService;
}

 

 

4、还有一种特别的读取方式:通过类名静态去获取。

这种方式的有效性与 spring-boot-starter-parent版本有关,若是

<version>1.5.2.RELEASE</version>

则读取不到。当前测试版本使用的是 <version>2.0.5.RELEASE</version>能够读取到。

 

@Component
@PropertySources(@PropertySource(value = "classpath:/service.properties"))
public class PropertiesStateReadService {

    private static Logger logger = LoggerFactory
            .getLogger(PropertiesStateReadService.class);
    public static String NAME = "name";
    public static Integer AGE = 1;

    @Value("${info.age}")
    public void setAGE(Integer aGE) {

        AGE = aGE;
    }
    @Value("${info.name}")
    public void setNAME(String nAME) {
        logger.info("save name ................");
        NAME = nAME;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值