SpringBoot讀取配置文件
一、 使用環境變量來獲取配置參數
application.yml配置文件中寫入下面信息
user: name: zhangsan age: 18
可以直接使用環境變量獲取參數。需要什么get什么屬性就行
public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(ScanApplication.class, args); System.out.println(ctx.getEnvironment().getProperty("user.name")); System.out.println(ctx.getEnvironment().getProperty("user.age")); }
二、使用bean獲取配置參數
@Component public class PropUtils implements ApplicationRunner { @Autowired private Environment env; @Override public void run(ApplicationArguments args) throws Exception { System.out.println(env.getProperty("user.name")); System.out.println(env.getProperty("user.age")); } }
打印結果同上
三、使用注解方式獲取配置參數
@Component public class PropUtils implements ApplicationRunner { @Value("${user.name}") private String userName; @Value("${user.age}") private Integer age; @Override public void run(ApplicationArguments args) throws Exception { System.out.println(userName); System.out.println(age); } }
打印結果同上
四、使用@PropertySource獲取屬性
@Configuration @PropertySource("classpath:application.yml") @ConfigurationProperties(prefix = "user") public class PropUtils implements ApplicationRunner { @Value("${name}") private String userName; @Value("${age}") private Integer age; @Override public void run(ApplicationArguments args) throws Exception { System.out.println(userName); System.out.println(age); } }
打印結果同上
五、讀取基本類型數組
配置文件添加下面內容:
ccc: week[0]: 星期日 week[1]: 星期一 week[2]: 星期二
然后代碼如下
@Data @Configuration @PropertySource("classpath:application.yml") @ConfigurationProperties(prefix = "ccc") public class PropUtils implements ApplicationRunner { List<String> week = new ArrayList<>(); @Override public void run(ApplicationArguments args) throws Exception { System.out.println(week); } }
打印結果:
六、讀取非默認配置文件的屬性
6.1 讀取prop文件屬性
新建文件conf-item.prop
cc.type=wwww aa.week[0]=星期日 aa.week[1]=星期一 aa.week[2]=星期二
java讀取代碼如下
@Data @Slf4j @Configuration @PropertySource(value = "classpath:conf-item.prop") @ConfigurationProperties(prefix = "aa") public class PropUtils implements ApplicationRunner { @Value("${cc.type}") String ccc; List<String> week = new ArrayList<>(); @Override public void run(ApplicationArguments args) throws Exception { log.info("ccc:{}",ccc); log.info("week:{}",week); } }
讀取出來可以看到是亂碼的,如下:
在@propertySource,就正常了
@PropertySource(value = "classpath:conf-item.prop",encoding = "UTF-8")
6.2 讀取yml文件屬性
讀取默認配置文件application.yml可以正常讀取,如果是自己新建的配置文件則會讀取失敗。
因為@PropertySource默認是使用DefaultPropertySourceFactory,讀取=號格式的文件。如果需要讀取yml文件則需要重寫這個類。

import java.io.IOException; import java.util.Optional; import java.util.Properties; 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.DefaultPropertySourceFactory; import org.springframework.core.io.support.EncodedResource; public class CompositePropertySourceFactory extends DefaultPropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename()); if (!resource.getResource().exists()) { // return an empty Properties return new PropertiesPropertySource(sourceName, new Properties()); } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) { Properties propertiesFromYaml = loadYaml(resource); return new PropertiesPropertySource(sourceName, propertiesFromYaml); } else { return super.createPropertySource(name, resource); } } /** * load yaml file to properties * * @param resource * @return * @throws IOException */ private Properties loadYaml(EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); factory.afterPropertiesSet(); return factory.getObject(); } }
讀取的時候指定下使用這個類即可。
@PropertySource(value = "classpath:conf-item.yml", factory = CompositePropertySourceFactory.class)
新建配置文件conf-item.yml如下
cc: type: ftp aaa: week[0]: 星期日 week[1]: 星期一 week[2]: 星期二
然后讀取文件方式如下:
import com.alibaba.fastjson.JSONObject; import com.wasu.scan.entity.ConfItem; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import java.util.ArrayList; import java.util.List; @Data @Slf4j @Configuration @PropertySource(value = "classpath:conf-item.yml", factory = CompositePropertySourceFactory.class) @ConfigurationProperties(prefix = "aaa") public class PropUtils implements ApplicationRunner { @Value("${cc.type}") String ccc; List<String> week = new ArrayList<>(); List<ConfItem> confItems = new ArrayList<>(); @Override public void run(ApplicationArguments args) throws Exception { log.info("ccc:{}",ccc); log.info("week:{}",week); } }
打印如下:
參考文章:
https://blog.csdn.net/wjw_77/article/details/90210942
https://blog.csdn.net/github_35169934/article/details/78233421