SpringBoot主流读取配置文件四种方式(新增更强大读取方式)

6,585 阅读1分钟

读取配置SpringBoot配置文件四种方式(新增更强大读取方式)

一、利用Bean注解中的Value(${})注解

@Data
@Component
public class ApplicationProperty {
    @Value("${application.name}")
	private String name;
}

该方式可以自动读取当前配置文件appliation.yml 或者application.properties中的配置值

区别在于读取yml文件时候支持中文编码,peoperties需要转码

二、利用@ConfigurationProperties(prefix = "developer")注解

@Data
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
	private String name;
	private String website;
	private String qq;
	private String phoneNumber;
}

该方式直接将当前加载yml配置文件前缀为developer的属性

读取developer.name...

pom文件中引入依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
</dependency>

三、前两种读取配置的使用方式

//使用方法
private final ApplicationProperty applicationProperty;
private final DeveloperProperty developerProperty;

@Autowired
	public PropertyController(ApplicationProperty applicationProperty, DeveloperProperty developerProperty) {
		this.applicationProperty = applicationProperty;
		this.developerProperty = developerProperty;
	}

@GetMapping("/property")
	public Dict index() {
        System.out.println("name:"+applicationProperty.getName());
        System.out.println("version:"+applicationProperty.getVersion());
        System.out.println("DevName:"+applicationProperty.getDeveloperName());
	}

四、用Hutool的方式读取配置文件(不支持yml格式)

1.用Props的方式读取

static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8);

2.用Setting的方法读取

static Setting setting = new Setting("application-dev.yml", CharsetUtil.CHARSET_UTF_8,true);

3.将配置文件读取

public class Constant {
    
    static Props props1 = new Props("application.properties",CharsetUtil.CHARSET_UTF_8);

    static Setting setting = new Setting("application-dev.properties", CharsetUtil.CHARSET_UTF_8,true);

    public static final String Name ;
    public static final String SettingName ;

    static {
        Name = props.getStr("application.name");
        SettingName = setting.getByGroup("name","application");

    }
}

4.使用方式

System.out.println(Constant.DevName+"------"+Constant.DevWebsite);

直接用常量类调用该类属性即可使用

五、用@PropertySource注解的方式读取配置文件(所有格式配置文件都支持)

@Configuration
@Component
@PropertySource(value = {"application.yml"})
@Data
public class ApplicationProperty_PropertySource {
	@Value("${server.port}")
	private String port;

	@Value("${spring.profiles.active}")
	private String active;

}

直接使用注解@PropertySource读取classPath下任意配置文件,也可以读取非classPath路径下,可以自定义。用法跟上述方法一致。使用spring框架中自带依赖即可使用。