spring boot(2) 配置項的賦值


 

1.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

	<!--
    	這里引用了我自建的父類包,如果沒有,可以把父類的pom里面的內容復制到這里來直接引包,
    	我建一個父類包是為了后面還有很多小項目不用每次都倒,這樣把相同公共的包放父類里面
     -->
  <parent>
        <artifactId>springBoot</artifactId>
        <groupId>com.guilf</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>springBoot2</artifactId>
</project>

2.Application.java  (這里的名字可以改,但最后固定一下)如果application.properties的配置文件換了位置,則要下面的改變

package com.guilf;

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

/**
 * Created by guilf on 2018/8/1.
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        // 注意:如果改變了spring boot 配置文件的位置,在啟動的時候指定位置
        //       測試時,@RunWith(SpringRunner.class)
        //               @SpringBootTest(classes= PlutoIsOmsWebApplication.class)
        //               @TestPropertySource(locations="classpath:conf/env/application.properties")
        //        也需要指定下;
        // System.setProperty("spring.config.location","classpath:conf/env/application.properties");
        SpringApplication.run(Application.class,args);
    }
}

3.1。配置項application.properties (數組傳值)

# 引用數組
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

4.1 接收上面的數組 建一個控制層 ArrayBindProperties.java  下面的@ConfigurationProperties(prefix ="my")中的my對象配置項里面的my,屬性值對應配置項的后面

package com.guilf.springBoot2;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ArrayBindProperties
 * @Description: (綁定數組)
 * @author guilf on 2018/8/1.
 * @version v1.1
 */
@Component
@ConfigurationProperties(prefix ="my")
public class ArrayBindProperties {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }

}

 5.1,ApplicationTest.java 測試類@SpringBootTest(classes ={Application.class})這里吧上面的application文件引進來了

package com.guilf.springBoot2;

import com.guilf.Application;
import com.guilf.springBoot2.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
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.SpringJUnit4ClassRunner;



/**
 * Created byguilf on 2018/8/1.
 */
@RunWith(SpringJUnit4ClassRunner.class)
/** @SpringBootTest 在1.4 版本后替換@SpringApplicationConfiguration(Application.class) 加載當前spring boot 環境  **/
@SpringBootTest(classes ={Application.class})
public class ApplicationTest {

    private static final Log log = LogFactory.getLog(ApplicationTest.class);

   

    @Autowired
    private ArrayBindProperties arrayBindProperties;
    // 測試數組
    @Test
    @Ignore
    public void arrayBind(){
    	System.out.println(arrayBindProperties.getServers());
    }
}

  6.1測試結果

3.2 配置項application.properties (屬性傳值)

com.guilf.title=hello world
#參數的引用
com.guilf.text=${com.guilf.title}
tt=123
# 隨機字符串
com.guilf.value=${random.value}
# 隨機int
com.guilf.number=${random.int}
# 隨機long
com.guilf.bignumber=${random.long}
# 10以內的隨機數
com.guilf.test1=${random.int(10)}
# 10-20的隨機數
com.guilf.test2=${random.int[10,20]}

4.2 ConfigProperties.java

 

package com.guilf.springBoot2;

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

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: BlogProperties
 * @Description: (自定義properties 屬性值映射類)
 * @author guilf on 2018/8/1
 * @version v1.1
 */
/** 使用@Component 注解為spring 管理的類,那么在別的類才可以進行注入使用。**/
@Component
/**
  當我們不是使用的默認的application.properties文件時,需要locations指定了我們要使用的配置文件路徑和名稱,
  可以這么定義:ConfigurationProperties(locations="classpath:config/company.properties")。
  1.5.x 不再這么支持,請使用
 @PropertySource(ignoreResourceNotFound = true, value = "classpath:conf/application.properties")
 **/
public class ConfigProperties {

    @NotNull
    @Value("${com.guilf.title}")
    private String name;

    @Value("${com.guilf.text}")
    private String text;

    @Value("${com.guilf.value}")
    private String value;
    @Value("${com.guilf.number}")
    private Integer number;
    @Value("${com.guilf.bignumber}")
    private Long bignumber;
    @Value("${com.guilf.test1}")
    private Integer test1;
    @Value("${com.guilf.test2}")
    private Integer test2;

    /**
     *  ${key:defaultVlaue} 表示在對應key 不成在時的默認值
     */
    @Value("${tt:test}")
    private String tt;

    public String getName() {
        return name;
    }

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

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public Long getBignumber() {
        return bignumber;
    }

    public void setBignumber(Long bignumber) {
        this.bignumber = bignumber;
    }

    public Integer getTest1() {
        return test1;
    }

    public void setTest1(Integer test1) {
        this.test1 = test1;
    }

    public Integer getTest2() {
        return test2;
    }

    public void setTest2(Integer test2) {
        this.test2 = test2;
    }

    public String getTt() {
        return tt;
    }

    public void setTt(String tt) {
        this.tt = tt;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

  5.2 ApplicationTest.java 也添加

@Autowired
    private ConfigProperties configProperties;
    @Test
    //@Ignore
    public void test(){
        log.info("=========================configProperties========================="+configProperties.getName());
        log.info("隨機數測試輸出:");
        log.info("隨機字符串 : " + configProperties.getValue());
        log.info("隨機int : " + configProperties.getNumber());
        log.info("隨機long : " + configProperties.getBignumber());
        log.info("隨機10以下 : " + configProperties.getTest1());
        log.info("隨機10-20 : " + configProperties.getTest2());
        log.info("在配置文件中沒有定義key的情況下,blogProperties 中給定默認值:"+configProperties.getTt());
        log.info("properties 參數引用:"+configProperties.getText());
    }

  6.2 內容

 

 3.3 有時項目分開發,測試和預發。這樣配置的參數可能就不一樣,這樣我們可以建多個配置文件

不同文件里面可以配置不同的參數  ,只是參數內容可能不一樣

# 服務端口
spring.server.address=192.168.6.204
spring.server.port=2222

application.properties里面則是 其實(test,prod和dev)就是對應的里面的文件

# 多環境配置文件激活屬性 不同的值到不同的地方
spring.profiles.active=test

  

4.3 

@PropertySource(ignoreResourceNotFound = true, value = "classpath:conf/${spring.profiles.active}/application-${spring.profiles.active}.properties")
這里面的value就拼接了字符串,把application.properties里面的text 替換${spring.profiles.active} value值就是classpath:conf/test/application-test.properties 就對應了路徑
@ConfigurationProperties(prefix = "spring.server")這里面的spring.server 就是對應的上面服務端口的前綴
package com.guilf.springBoot2;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @ClassName: ProfileProperties
 * @Description: (獲取多環境下的屬性參數)
 * @author guilf on 2018/8/1.
 * @version v1.1
 */
@Component
@ConfigurationProperties(prefix = "spring.server")
// 指定對應的配置文件的路徑 value是拼接路徑地方
@PropertySource(ignoreResourceNotFound = true, value = "classpath:conf/${spring.profiles.active}/application-${spring.profiles.active}.properties")
public class ProfileProperties {

    private String address;

    private String port;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

5.3,在測試類加上

 @Autowired
    private ProfileProperties profileProperties;
    @Test
    public void testProfile(){
         log.info("當前環境的ip地址:"+profileProperties.getAddress());
         log.info("當前環境的端口:"+profileProperties.getPort());
    }

  

 6.3,測試內容

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM