active:
author: weiyuanbao
envList:
- acc: 10766
a: 10.11
erl: 10.167
- acance: 10.8766
accier: 10.101
- 使用 @PropertySource 和 @ConfigurationProperties 注解 将配置加载为一个 Bean
import com.manhattan.autotest.config.MixPropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
import java.util.Map;
@Data
@Configuration
@PropertySource(value = {"classpath:active.yml"}, factory = MixPropertySourceFactory.class)
@ConfigurationProperties(prefix = "active")
public class EnvUrl {
public String author;
public List<Map<String, String>> envList;
}
- Springboot @PropertySource 不支持加载 yml 配置文件,所以需要自定义一个配置类
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 org.springframework.lang.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
public class MixPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) {
List<PropertySource<?>> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
return yamlSources.get(0);
} else {
return new DefaultPropertySourceFactory().createPropertySource(name, resource);
}
}
}
@Autowired
EnvUrl envUrl;
@Test
void test() {
System.out.println(envUrl.toString());
System.out.println(envUrl.author);
System.out.println(envUrl.envList.toString());
}