springboot的两种核心配置文件application.properties和application.yml
实体类:
@Component
@ConfigurationProperties(prefix = "person")//默认从全局配置文件中获取值,全局文件中没有的话从@PropertySource指定的路径获取
public class Person {
// @Value("${person.last-name}")
private String lastName;
private Integer age;
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog.getName() +
'}';
}
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getBoss() {
return boss;
}
public void setBoss(Boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
application.properties的使用代码,如
#server.port=8081
#idea,properties默认文件utf-8
#person.last-name=张三
#person.age=12
#person.birth=2019/03/12
#person.boss=false
#person.dog.name=dog
#person.lists=a,b,c
#person.maps.k1=v1
#person.maps.k2=v
application.yml这种配置方式需要加空格,如
person:
age: 12
last-name: lisi
birth: 2000/08/21
maps: {k1: v1,k2: v2}
boss: false
lists:
- lisi
- wu
dog:
name: 唐三
# lists: [lisi,sfesdf]行内
server:
port: 8081
常用注解
@ConfigurationProperties:是springboot提供读取配置文件的一个注解
@Value:把配置文件的值注入到该属性中相当于set方法
使用以上两个注解均需要使用配置文件,@ConfigurationProperties访问配置文件需要加前缀如:@ConfigurationProperties(prefix = “person”),配置文件如:application.properties(一般不写在这个核心配置文件中,都是自己创建一个xxx.properties)
使用@Value获取数据时都需要加上你自定义的类名.属性获取,如
@Value("${person.last-name}")
@PropertySource从配置文件中获取值,如
@PropertySource(value = {“classpath:person.properties”})
Bean的使用
Springboot创建bean如果不做一些配置是无效的,我这里给大家介绍两种
(1) 使用注解的方式,如
@ImportResource(locations = {“classpath:beans.xml”})
(2)定义一个配置类,如
@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public PersonService personService(){
return new PersonService();
}
}