配置文件相关-
1、@ConfigurationProperties(prefix = “hpf”)
1.定义yml/properties文件
hpf:
name: zhangsan
age: 12
2.定义映射类
@Component
@ConfigurationProperties(prefix = "hpf")
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注意:默认从全局配置文件中获取值
2、@Value使用
/**
* @author hanpengfei1
* @date 2020/3/13 21:40
*/
@Component
//@ConfigurationProperties(prefix = "hpf")
public class User {
@Value("${hpf.name}")
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注意:默认从全局配置文件中获取值,以上方式均能讲配置文件中的属性值映射到bean中。
3、@PropertySource&ImportResource
@PropertySource(value={"classpath:person.properties"}) //从指定属性文件中读取属性
@ImportResource(locations = {"calsspath:beans.xml"}) //导入spring的配置文件,让配置文件里的内容生效;springboot里面没有配置文件,我们自己的配置文件也不能自动识别,需要此注解导入
resources/beans.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.hpf.study.springbootdemo.service.HelloService"></bean>
</beans>
resources/person.properties
person.name=lisi
person.age=121
4、springboot推荐给容器中添加组件的方式
-
配置类@Configuration ====相当于之前的spring配置文件
-
@Bean
/** * @author hanpengfei1 * @date 2020/3/13 22:53 */ @Configuration // 指明当前是一个配置类,相当于之前的配置文件。 public class MyAppConfig { @Bean public HelloService helloService(){//用方法名作为 bean id return new HelloService(); } }
5、配置文件加载位置
springboot 启动会扫描以下位置的application.properties或application.yml文件作为spring boot的默认配置文件
-
file:./config/
-
file:./
-
classpath:./config/
-
classpath:./
以上按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置会覆盖低优先级配置内容
也可以通过配置spring.config.location来改变默认配置
6、外部配置加载顺序
优先级从高到底,高优先级配置覆盖低优先级配置
-
命令行参数
-
来自java:comp/env属性
-
Java系统属性(system.getProperties)
-
操作系统环境变量
-
RandomValuePropertySource配置的random.*属性值
-
jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
-
jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
-
jar包外部的application.properties或application.yml
-
jar包内部的application.properties或application.yml
-
@Configuration注解类上的@PropertySource