天天看點

3.Springboot中@ConfigurationProperties和@Value的差別

1.結構圖

3.Springboot中@ConfigurationProperties和@Value的差別

1.Person實體類

package com.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/*
* 将配置檔案中配置的每一個屬性的值,映射到這個元件中
*   @ConfigurationProperties:
*       告訴springboot容器将本類中所有的屬性和配置中檔案相關的配置進行綁定;
*           prefix = "person";配置檔案中哪個下面的所有屬性進行一一映射
*
*   隻有這個元件是容器的元件,才能容器提供的@ConfigurationProperties功能:
* */
@Component
//@ConfigurationProperties(prefix = "person")
public class Person {
/*
 * <bean class="Person">
      <property name="LastName" value="字面量/${key}從環境變量、配置檔案中擷取值/#{SpEl}"><property>
   <bean/>
 *   這裡的注解value就相當于這個值 = value="字面量/${key}從環境變量、配置檔案中擷取值/#{SpEl}"
 * */
//    @Value("${person.last-name}")
    private String lastName;
//    @Value("#{11*2}")
    private Integer age;
//    @Value("true")
    private Boolean boss;
//    @Value("2078/12/11")
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> list;
    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> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
    /*
    * alt+insert:快捷鍵建立GetSet方法
    */
    /*
    * 總結:
    * @ConfigurationProperties 是批量擷取值并且綁定的,并且支援松散綁定
    * @Value是挨個值注入,不支援松散綁定(必須是last-name,不可以是lastName【也就是要和配置檔案裡的一樣,不一樣就會報錯】)
    *
    *
    * */
}
           

2.Dog實體類

package com.bean;

public class Dog {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
           

3.表現層HelloController(單獨使用@Value的時候,單獨注入單獨使用)

package com.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/*
* 一個注解@RestController = @Controller + @ResponseBody
*
* */
@RestController
public class HelloController {
    //當單獨得使用一個值得時候就可以使用@Value注入一個值就行
    //其他都是使用@ConfigurationProperties(prefix = "person")批量注入就可以
    @Value("${person.last-name}")
    private String name;

    @RequestMapping("/sayHello")
    public String sayHello(){
        return "Hello 你好 "+name;
    }
}
           

4.主運作配置類ControllerApplication

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ControllerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ControllerApplication.class, args);
    }

}
           

5.配置檔案(兩者選其一)application.properties/application.yml

#server.port=8081
#idea中的properties預設是ACSII,現在是utf-8要轉成ACSII
#idea中的properties的bean檔案person不會提示,但是能運作 這就離譜,我百度了一下解決不了我這個為什麼不能自動提示的問題
person.last-name=張三
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
           

application.yml(層級分明)

person:
  lastName: 哈哈
  age: 25
  #打錯字母就報錯:lang.IllegalStateException: Failed to load ApplicationContext
  boss: false
  birth: 2019/12/19
  maps: {k1: v1,k2: 19}
  list:
    - lisi
    - zhaoliu
    - zhou
  dog:
    name: 小猴
    age: 2
           

6.測試類(自動生成)

package com.bean;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/*
*   springboot單元測試
*       可以在測試期間很友善的類似編碼一樣進行自動注入等容器的功能
*
* */
@SpringBootTest
class ControllerApplicationTests {

    @Autowired
    Person person;

    @Test
    void contextLoads() {
        System.out.println("資料"+person);
    }

}
           

7.依賴pom.xml(依賴自動幫你把基礎的依賴加好)

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--導入配置檔案處理器,配置檔案綁定就會有輸入提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
           

差別:也就是可以說:經常使用的還是@ConfigurationProperties,單獨使用就用@Value

3.Springboot中@ConfigurationProperties和@Value的差別
3.Springboot中@ConfigurationProperties和@Value的差別

總結:

1.自己的練習過程,有錯誤和問題歡迎來讨論

2.快速建立不成功,建議換下網絡,因為快速建立和網絡有關

繼續閱讀