springboot读取配置文件

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

1.通过@Value注解来读取

application.properties文件内容:

name=1

user.name=2

读取方式:

@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> 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;
}

你可能感兴趣的:(java,java,spring,spring,boot)