springboot採納了創建生產就緒Spring應用程序的觀點。 Spring Boot優先於配置的慣例,旨在讓您儘快啓動和運行。在通常狀況下,咱們不須要作太多的配置就可以讓spring boot正常運行。在一些特殊的狀況下,咱們須要作修改一些配置,或者須要有本身的配置屬性。java
當咱們建立了SpringBoot-maven 項目後,自動生成 src/main/resources/application.properties(application.yml) 配置文件進行spring的配置
配置自定義屬性 :spring
配置服務啓動的端口號 : server.port=8000 (application.properties) server : (application.yml) port : 8000
讀取配置文件的屬性springboot
定義普通的java對象 public class Student{ private String name; private Integer age; private String sex; // 省略 getter setter 方法 } @RestController @RequestMapping("student") public class StudentController { @Value("${student.name}") private String name; @Value("${student.age}") private Integer age; @RequestMapping("index1") public Student index1(){ Student student = new Student(); student.setAge(age); student.setName(name); return student; } } 訪問 localhost:8000/student/index1 name以及age注入進來
讀取配置文件注入到javaBean中,使用ConfigurationProperties(prefix="student") 不用再使用@Value("${name}") 設置值,而且得添加一個依賴.另外須要在應用類或者application類,加EnableConfigurationProperties註解。app
@Component @ConfigurationProperties(prefix = "student") public class Student { private String name; private Integer age; private String sex; // 省略 getter setter方法 } @RestController @RequestMapping("student") @EnableConfigurationProperties({Student.class}) public class StudentController { @Autowired private Student student; @RequestMapping("index2") public Student index2(){ System.out.println("0000"); return student; } } <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
自定義配置文件(不適用默認的application.properties)dom
- 新建配置文件(${random.xxx} 獲取隨機數) test.properties users.name=name users.age=${random.int} users.max=${random.int(20)} users.uuid=${random.uuid} users.hi=hi users.value=Hello,${users.name} - 在須要注入的javaBean 上添加註解(@PropertiesSource(value="classpath:test.properties") @ConfigurationProperties(profix="users")) @Component @PropertySource("classpath:test.properties") @ConfigurationProperties(prefix = "users") public class Users { private String name; private Integer age; private String uuid; private String value; private Integer max; private String hi; } - **使用自定義的 test.yml 一直沒有注入成功** - 使用 在controller中添加 @EnableConfigurationProperties({Users.class}) @RestController @RequestMapping("user") @EnableConfigurationProperties({Users.class}) public class UserController { @Autowired private Users users; @RequestMapping("index3") public Users index3(){ return users; } } - 多個環境配置文件 1. 在現實的開發環境中咱們可能須要多個不一樣環境(開發,調試,生產)的配置文件能夠使用 application-{profile}.properties進行配置如 application-dev.properties : 開發環境 application-test.properties : 測試環境 application-prod.properties : 生產環境 2. 使用 : 在application.properties中配置 spring.profiles.active=dev 表示啓動 開發環境 3. 啓動程序發現端口變成了 dev 下配置的