spring boot(版本1.5.1.RELEASE)项目中,当准备映射自定义的配置文件属性到类中的时候,发现原本的@ConfigurationProperties注解已将location属性移除,因此导致无法正常给配置类的属性赋值。

在为移除之前使用方法如下:

@ConfigurationProperties(prefix = "remote",locations={"classpath:remote.properties"}) 

解决方案一

之所以废除该方式,是因为spring boot认为将一个配置类绑定到一个配置文件是一件不好的事。

此时可以使用在配置类中采用@Component的方式注册为组件,然后使用@PropertySource来指定自定义的资源。

@Component
@PropertySource({"classpath:remote.properties"})
@ConfigurationProperties(prefix = "remote")
public class RemoteConfig {

	/**
	 * 远程服务地址
	 */
	private String address;

	/**
	 * 远程服务端口
	 */
	private int port;
	
    // getter/stetter方法
}

解决方案二

在启动的时候指定需要读取的配置文件名称不管你的配置文件是yaml、还是yml,都只需要指定名称,不需要后缀。

new SpringApplicationBuilder(Application.class)
    .properties("spring.config.name=application,mine")
    .run(args);

当然如果有很多的配置文件,可以考虑如下方式。以后有新的配置文件需要读取,直接在数组里面添加就可以了。

public static String getConfigNamesProperties() {
    String[] configNameArray = {
            "aaa",
            "bbb",
            "ccc",
            "ddd",
            "eee",
            "fff"
    };

    String configNames = StringUtils.join(configNameArray, ",");
    return "spring.config.name=" + configNames;
}

启动中读取修改:

new SpringApplicationBuilder(ReturnCenter.class)
                .properties(getConfigNamesProperties())
                .run(args)

其他相关使用方式不变。

Spring技术视频

CSDN学院:《Spring Boot 视频教程全家桶》

spring boot @ConfigurationProperties废弃location属性插图
公众号:程序新视界


spring boot @ConfigurationProperties废弃location属性插图1

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.choupangxia.com/2019/12/25/spring-boot-configurationproperties-location/