在SpringBoot里能够经过四个注解进行配置文件的注入,分别是:java
@ConfigurationProperties @Value @PropertySource @ImportResourcespring
居中好比个人配置文件application.yml里面是这种springboot
person: lastName: hello age: 18 boss: false birth: 2017/12/12 maps: {k1: v1,k2: 12} lists: - lisi - zhaoliu dog: name: 小狗 age: 12
JavaBeanapp
/** - 将配置文件中配置的每个属性的值,映射到这个组件中 - @ConfigurationProperties:告诉SpringBoot将本类中的全部属性和配置文件中相关的配置进行绑定;prefix = "person":指定 配置文件中哪一个前缀下面的全部属性进行 一一 映射 - 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能, - 使其成为组件能够经过下面的两种中的任何一种方式 1.@Component //若是这里添加了注解那么在自动配置类的时候就不用添加 2.@EnableConfigurationProperties(Person.class)注解. */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; }
@Value 只能从application.yml中读取spring-boot
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person { //lastName必须是邮箱格式 @Email @Value("${person.last-name}") private String lastName; @Value("#{11*2}") private Integer age; @Value("true") private Boolean boss;
若是说,咱们只是在某个业务逻辑中须要获取一下配置文件中的某项值,使用@Value; 若是说,咱们专门编写了一个javaBean来和配置文件进行映射,咱们就直接使用@ConfigurationProperties;ui
@PropertySource:加载指定的配置文件(非application.yml);必需要加 @Component,让其spring进行管理 须要配合@ConfigurationProperties(prefix = "") 指定prefix 绑定到JavaBean中spa
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能; * @ConfigurationProperties(prefix = "person”) 默认从全局配置文件中获取值 即默认只能从 application.properties 或者 application.yml 中获取; * */ @Component @ConfigurationProperties(prefix = "person") @PropertySource(value = {"classpath:person.properties"}) @Data public class PersonConfig { private String lastName; private String firstName; }
person.properties 文件code
person.lastName=johnny persong.firstName=candy
导入Spring的配置文件 xml 格式的 放在 主运行类上,Spring Boot里面没有Spring的配置文件,咱们本身编写的配置文件,也不能自动识别xml
想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上blog
@ImportResource(locations = {"classpath:bean.xml"}) @SpringBootApplication public class SpringBoot01HelloworldQuickApplication { } bena.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean> </beans>
做用: 配置文件处理器的主要做用是为了 在编写配置文件的时候有提示功能
<--导入配置文件处理器,配置文件进行绑定就会有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
我的博客系统:https://www.askajohnny.com 欢迎访问! 本文由博客一文多发平台 OpenWrite 发布!