spring boot自动读取配置功能很方便,但当配置内容过大时,需要分文件进行维护,否则维护不方便。多个配置文件时使用@PropertySource注解进行指定配置文件名,但此注解默认解析properties文件,无法解析yaml,显示结果为null。
虽然默认无法解析,但提供了factory配置,我们可以通过配置此参数来实现。
首先实现接口PropertySourceFactory
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.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
factoryBean.setResources(encodedResource.getResource());
factoryBean.afterPropertiesSet();
Properties ymlProperties = factoryBean.getObject();
String propertyName = s !=null ? s: encodedResource.getResource().getFilename();
return new PropertiesPropertySource(propertyName, ymlProperties);
}
}
然后在基类的**@PropertySource**注解上加上 factory = YamlPropertySourceFactory.class
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource(value = "classpath:workWX.yml", encoding = "UTF-8", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "wx")
public class WXWorkConfig {
public String corpId;
private String corpSecret;
private String departmentId;
private String fetchChild;
private String url;
private String getToken;
private String getUserList;
}
效果