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,测试内容

 

猜你喜欢

转载自www.cnblogs.com/guilf/p/9399813.html