springBoot读取配置文件

一.读取springboot框架自带的application.properties或application.yml文件。

application.properties文件内容:
name=name
user.name=userName

1.通过@Value注解来读取

读取方式:

@Value("${name}")
private String name;
 
@Value("${user.name}")
private String userName;
如果要设置默认值:

@Value("${name:张三}")
private String name;
 
//设置默认值为空置
@Value("${user.name:#{null}}")
private String userName;

2.通过@ConfigurationProperties(prefix=“***”)来读取

@Data
@Component
@ConfigurationProperties(prefix="user")
public class TestBean{
 
    String name;
}

二.读取springboot中自定义的properties文件,例如test.properties

1.通过@Value和@PropertySource结合取值

@Component
@PropertySource("classpath:test.properties")
public class TestBean{
 
    @Value("${name}")
    private String name;
 
    @Value("${user.name}")
    private String userName;
}

2.通过@ConfigurationProperties和@PropertySource结合取值

@Component
@ConfigurationProperties(prefix="user")
@PropertySource("classpath:test.properties")
public class TestBean{
    String name;
}

三.读取springboot中自定义的yml文件,例如test.yml

1.通过@Value和@PropertySource

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
 
import java.io.IOException;
import java.util.List;
 
public class PropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}
 
@Component
@PropertySource(value="test.yml",factory=PropertySourceFactory.class)
public class TestBean{
 
    @Value("${name}")
    private String name;

版权声明:本文为Chat_FJ原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。