springboot配置文件加载
这里是springboot加载相应文件汇总内容,内容持续更新。
一、yml文件加载
1 yml文件案例
server:
servlet:
context-path: /spring-web
port: 8081
person:
username: 张三
age: 18
birth-date: 2020/8/3
hobby: ["篮球","听歌","写作"]
others:
key1: value1
key2: value2
work-contents:
- key1: key11
- key2: key22
加载方式: 使用@ConfigurationProperties注解
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String username;
private Integer age;
private Date birthDate;
private List<String> hobby;
private Map<String,Object> others;
private List<Map<String,Object>> workContents;
... setter
... getter
}
# 测试案代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringMain.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringMainTest {
@Autowired
protected Person person;
@Test
public void test01() {
System.out.println(person);
//System.out.println(userService);
//System.out.println(helloService01);
}
}
效果如下:
Person{username='张三', age=18, birthDate=Mon Aug 03 00:00:00 CST 2020, hobby=[篮球, 听歌, 写作], others={key1=value1, key2=value2}, workContents=[{key1=key11}, {key2=key22}]}
二、加载普通的properties
person.username=李四
person.age=20
person.birthDate=2020/8/4
加载方式: 使用@PropertySource注解+@Value注解
@PropertySource(value = {"classpath:person.properties"},encoding = "UTF-8")
public class Person {
@Value("${person.username}")
private String username;
@Value("${person.age}")
private Integer age;
@Value("${person.birthDate}")
private Date birthDate;
效果如下:
Person{username=‘李四’, age=20, birthDate=Tue Aug 04 00:00:00 CST 2020, hobby=null, others=null, workContents=null}
三、加载bean配置文件
<?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="userService" class="com.walker.web.service.UserService"></bean>
</beans>
加载方式 :@ImportResource(locations = {“classpath:bean.xml”})
@ImportResource(locations = {"classpath:bean.xml"})
public class SpringMain {
public static void main(String[] args) {
SpringApplication.run(SpringMain.class,args);
}
}