关于springboot application文件配置
properties文件生效顺序
springboot YAML固定属性配置
固定属性(比如图片存放路径,文件存放路径等。)
pom.xml文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
User.java文件
package org.sang;
import java.util.List;
/**
* Created by sang on 2018/7/5.
*/
public class User {
private String name;
private String address;
private List<String> favorites;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<String> getFavorites() {
return favorites;
}
public void setFavorites(List<String> favorites) {
this.favorites = favorites;
}
}
Users.java文件
注意配置
@Component
和@ConfigurationProperties(prefix = “my”)
这两个注解关联application.yml中数据
@ConfigurationProperties 中的 prefix 性描述了要加载的配置文件的前缀。
package org.sang;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by sang on 2018/7/5.
*/
@Component
@ConfigurationProperties(prefix = "my")
public class Users {
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
application.yml
my:
users:
- name: 江南一点雨
address: China
favorites:
- 足球
- 徒步
- Coding
- name: sang
address: GZ
favorites:
- 阅读
- 吉他
Test.java
注意
@Autowired
Users users;
使用spring注入对象
package org.sang;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Iterator;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter021ApplicationTests {
// @Autowired
// User user;
@Autowired
Users users;
@Test
public void contextLoads() {
// System.out.println(user);
System.out.println(users);
for (Iterator<User> it = users.getUsers().iterator(); it.hasNext();) {
User user = it.next();
System.out.println("Item is: " + user.getName());
System.out.println("Item is: " + user.getAddress());
System.out.println("Item is: " + user.getFavorites());
}
}
}
springboot各组件详细配置(application.properties)
https://docs.spring.io/spring-boot/docs/
选择对应版本的
进入
https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/html/
搜索
Appendices
点击 Common application properties
完整链接
https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/html/common-application-properties.html