當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot配置文件与配置类的属性映射方式
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot配置文件与配置类的属性映射方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、在pom文件中加入依賴
目錄結(jié)構(gòu)
在實體類中會出現(xiàn)錯誤,然后點擊這個網(wǎng)址會有需要的依賴
網(wǎng)址:
https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor
引入的依賴為:
二、application.yml
#配置對象 person:name: zhangsanage: 19date: 2019/09/09# 數(shù)組配置city:- beijing- tianjin- shanghai- chongqing# 配置集合 student: - name: zhangsanage: 18score: 100 - name: lisiage: 28score: 88 - name: wangwuage: 38score: 90 #注意事項:在key與value直接需要加入空格,對大小寫敏感。 server:port: 8081servlet:context-path: /demo三、application.properties
server.port=8081 server.servlet.context-path=/demo四、Person
需要提供get/set方法 和toString方法
還需要注解@Component
需要注解@ConfigurationProperties(prefix = “person”)
使用注解@Con?gurationProperties映射
通過注解@Con?gurationProperties(pre?x=’'配置文件中的key的前綴")可以將配置文件中的配置自動與實體進(jìn)行映 射。
使用@Con?gurationProperties方式必須提供Setter方法,使用@Value注解不需要Setter方法
五、HelloController
1、使用注解@Value映射
@value注解將配置文件的值映射到Spring管理的Bean屬性值
package com.william.day01_springboot_initializr.controller;import com.william.day01_springboot_initializr.domain.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;/*** @author :lijunxuan* @date :Created in 2019/6/27 17:20* @description :* @version: 1.0*/ @RestController public class HelloController {@AutowiredPerson person;@Value("${person.name}")private String name;@Value("${person.age}")private String age;@RequestMapping("/hello")public String hello(){return String.format("hello world 你好!世界!1234222 name = %s!! age = %s!! person = %s !!",name,age,person);// return String.format("hello world 你好!世界!1234222 person = %s !!",person);} }七、測試 結(jié)果
總結(jié)
以上是生活随笔為你收集整理的SpringBoot配置文件与配置类的属性映射方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 平版电脑手绘临摹软件(平板电脑手绘软件)
- 下一篇: 西昊电脑椅m18和m35(西昊m84椅子