Springboot读取配置文件


SpringBoot读取配置文件

一、 使用环境变量来获取配置参数

application.yml配置文件中写入下面信息

user:
  name: zhangsan
  age: 18

可以直接使用环境变量获取参数。需要什么get什么属性就行

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx =  SpringApplication.run(ScanApplication.class, args);
        System.out.println(ctx.getEnvironment().getProperty("user.name"));
        System.out.println(ctx.getEnvironment().getProperty("user.age"));
    }

二、使用bean获取配置参数

@Component
public class PropUtils implements ApplicationRunner {
    @Autowired
    private Environment env;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(env.getProperty("user.name"));
        System.out.println(env.getProperty("user.age"));
    }
}

打印结果同上

三、使用注解方式获取配置参数

@Component
public class PropUtils implements ApplicationRunner {

    @Value("${user.name}")
    private String userName;
    @Value("${user.age}")
    private Integer age;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(userName);
        System.out.println(age);
    }
}

打印结果同上

四、使用@PropertySource获取属性

@Configuration
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "user")
public class PropUtils implements ApplicationRunner {

    @Value("${name}")
    private String userName;
    @Value("${age}")
    private Integer age;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(userName);
        System.out.println(age);
    }
}

打印结果同上

五、读取基本类型数组

配置文件添加下面内容:

ccc:
  week[0]: 星期日
  week[1]: 星期一
  week[2]: 星期二

然后代码如下

@Data
@Configuration
@PropertySource("classpath:application.yml")
@ConfigurationProperties(prefix = "ccc")
public class PropUtils implements ApplicationRunner {

    List<String> week = new ArrayList<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(week);
    }
}

打印结果:

 

 

六、读取非默认配置文件的属性

6.1 读取prop文件属性

新建文件conf-item.prop

cc.type=wwww
aa.week[0]=星期日
aa.week[1]=星期一
aa.week[2]=星期二

java读取代码如下

@Data
@Slf4j
@Configuration
@PropertySource(value = "classpath:conf-item.prop")
@ConfigurationProperties(prefix = "aa")
public class PropUtils implements ApplicationRunner {

    @Value("${cc.type}")
    String ccc;

    List<String> week = new ArrayList<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ccc:{}",ccc);
        log.info("week:{}",week);
    }
}

读取出来可以看到是乱码的,如下:

 

 在@propertySource,就正常了

@PropertySource(value = "classpath:conf-item.prop",encoding = "UTF-8")

 

 6.2 读取yml文件属性

读取默认配置文件application.yml可以正常读取,如果是自己新建的配置文件则会读取失败。

因为@PropertySource默认是使用DefaultPropertySourceFactory,读取=号格式的文件。如果需要读取yml文件则需要重写这个类。

import java.io.IOException;
import java.util.Optional;
import java.util.Properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

public class CompositePropertySourceFactory  extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            // return an empty Properties
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYaml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    /**
     * load yaml file to properties
     *
     * @param resource
     * @return
     * @throws IOException
     */
    private Properties loadYaml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}
CompositePropertySourceFactory

读取的时候指定下使用这个类即可。

@PropertySource(value = "classpath:conf-item.yml",
        factory = CompositePropertySourceFactory.class)

新建配置文件conf-item.yml如下

cc:
  type: ftp


aaa:
  week[0]: 星期日
  week[1]: 星期一
  week[2]: 星期二

然后读取文件方式如下:

import com.alibaba.fastjson.JSONObject;
import com.wasu.scan.entity.ConfItem;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
@Configuration
@PropertySource(value = "classpath:conf-item.yml",
        factory = CompositePropertySourceFactory.class)
@ConfigurationProperties(prefix = "aaa")
public class PropUtils implements ApplicationRunner {

    @Value("${cc.type}")
    String ccc;

    List<String> week = new ArrayList<>();
    List<ConfItem> confItems = new ArrayList<>();



    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ccc:{}",ccc);
        log.info("week:{}",week);
    }
}

打印如下:

 

 

 

 

 

参考文章:

https://blog.csdn.net/wjw_77/article/details/90210942

https://blog.csdn.net/github_35169934/article/details/78233421

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM