Spring Boot-4核心配置文件application和自定义配置文件properties/yml的读取

  Spring-Boot的核心配置文件是application.properties或application.yml,文件名是写死的。可以根据自己习惯选择。他们都放在/src/main/resources路径下。当变量较少或者属于全局变量时候,我们通常会将它们放在核心配置文件中。如果变量较多或不属于全局变量,为了核心配置文件不显得冗余繁杂,我们自定义配置文件,存放这些变量。

  核心配置文件的读取

  

    

  先放两中文件的图,读取有两种方式:

  方式一:@Value

  在我上个博客讲过了,这次不再重复。传送门:点击打开链接

  方式二:Environment

  使用@Autowired引入,然后调用getProperty(String key)即可。如图:

  

  我们启动项目,访问http://localhost:8080/name

 

  自定义配置文件的读取 

  对于自定义配置文件,以properties结尾和yml结尾的我们分开讲。

  提出一个需求:我们项目需要定义一个学生的信息,包括姓名,年龄

扫描二维码关注公众号,回复: 1530931 查看本文章
  *.properties的读取

  我们在src/main/resources下创建一个config文件夹,在config下创建student.properties,创建Student.java

  

  

   

  这样就可以在controller里面使用了。使用@Autowired注入Student对象

  *.yml的读取

  

  

  启动项目,访问http://localhost:8080/name,发现:

  

 值为null,感觉很奇怪。百度很久发现是注解除了问题。查看官方文档:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-yaml-shortcomings

  @PropertySource不支持对yml的加载

  我们做以下改动,Student.java类上不再使用@PropertySource加载自定义的yml文件,将其删除。使用配置Bean的方式加载。

@Configuration
public class MyConfig {

	// 加载YML格式自定义配置文件
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		// yaml.setResources(new FileSystemResource("application-cat.yml"));// File引入
		yaml.setResources(new ClassPathResource("config/student.yml"));// class引入
		configurer.setProperties(yaml.getObject());
		return configurer;
	}

}

  启动项目,再次访问http://localhost:8080/name,发现正常

  


  

 
本博客为自己总结亦或在网上发现的技术博文的转载。 如果文中有什么错误,欢迎指出。以免更多的人被误导。
邮箱:[email protected]
版权声明:本文为博主原创文章,博客地址:https://blog.csdn.net/ChinaMuZhe,未经博主允许不得转载。

  

猜你喜欢

转载自blog.csdn.net/ChinaMuZhe/article/details/80608584