第一步
继承DefaultPropertySourceFactory 重写createPropertySource方法
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 YmlPropertyLoaderFactory 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());
if (sources.size() == 0) {
return super.createPropertySource(name, resource);
}
return sources.get(0);
}
}
第二步
获取自定义配置实体类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author Zhm
* @date 2022/5/31 11:03
**/
@Data
@Component
@PropertySource(value = {"classpath:config.yml"}, factory = YmlPropertyLoaderFactory.class, ignoreResourceNotFound = true)
@ConfigurationProperties(prefix ="ly.cors")
public class CorsProperties {
private List<String> allowedOrigins;
private Boolean allowedCredentials;
private List<String> allowedMethods;
private List<String> allowedHeaders;
private Long maxAge;
private String filterPath;
}
第三步
新建yml配置文件
ly:
cors:
allowedCredentials: true
allowedHeaders:
- '*'
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
- HEAD
allowedOrigins:
- http://xxx.xxx.xxx
filterPath: /**
maxAge: 3600