springboot支持.properties文件和.yml文件两种配置文件,此教程对.yml文件讲解
springboot默认加载配置文件的路径有很多,默认将配置文件放到resources目录下
更多详情可以参考官方文档
value获取属性
1.在application.yml中添加属性
注:冒号后面带一个空格
bean:
name: springboot
age: 20
2.获取属性
@Component
public class PropertiesBean {
@Value("${bean.name}")
private String name;
@Value("${bean.age}")
private Integer age;
// getter setter 省略
@Override
public String toString() {
return "PropertiesBean{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesApplicationTests {
@Autowired
private PropertiesBean bean;
@Test
public void loadBean() {
System.out.println(bean);
}
}
控制台:PropertiesBean{name='springboot', age=20}
使用@ConfigurationProperties注解赋值属性
1.获取属性
@ConfigurationProperties(prefix = "bean")
@Component
public class PropertiesBean1 {
private String name;
private Integer age;
// getter setter省略
@Override
public String toString() {
return "PropertiesBean1{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesApplicationTests {
@Autowired
private PropertiesBean1 bean1;
@Test
public void loadBean1() {
System.out.println(bean1);
}
}
控制台:PropertiesBean1{name='springboot', age=20}
注:如果实体类不加@Component,则需要在使用的类上加@EnableConfigurationProperties注解
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableConfigurationProperties({PropertiesBean1.class})
public class PropertiesApplicationTests {
@Autowired
private PropertiesBean1 bean1;
@Test
public void loadBean1() {
System.out.println(bean1);
}
}
使用自定义配置文件
如果不想在application.yml文件中配置属性,也可以在自定义的文件中配置
1.在resources目录下创建test.properties
test.name=spring-test
test.age=18
2.获取属性
@Configuration
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix = "test")
public class PropertiesBean2 {
private String name;
private Integer age;
// getter setter 省略
@Override
public String toString() {
return "PropertiesBean2{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesApplicationTests {
@Autowired
private PropertiesBean2 bean2;
@Test
public void loadBean2() {
System.out.println(bean2);
}
}
控制台:PropertiesBean2{name='spring-test', age=18}
使用Environment获取配置属性
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesApplicationTests {
@Autowired
private Environment env;
@Test
public void testEnvironment() {
System.out.println(env.getProperty("bean.name"));
}
}
控制台:springboot
外部配置
springboot项目是基于jar运行的,运行时设置参数
java -jar xxx.jar --server.port=8088
server.port=8088相当于在application.yml中设置启动端口
加载其他配置文件
在application.yml中引入其他文件
spring:
profiles:
include: db
注:引入文件名称需要是application-xx.yml,引入时只需要写xx即可
多环境配置
启动时配置
java -jar xxx.jar --spring.profiles.active=dev
注:配置文件名称需要时application-xx.yml格式
作者公众号
