SpringBoot从application.yml中获取自定义常量
2018-07-01 18:33:01
1275次阅读
0个评论
注意 application.yml 中不能用驼峰式写法(systemParams)要改成system-params

要导入依赖

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

application.yml


system-params:
  image-uri: http://xxxxxx


SystemParams


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

@Component
@ConfigurationProperties(prefix = "system-params")
public class SystemParams {

    private String imageUri;

    public String getImageUri() {
        return imageUri;
    }

    public void setImageUri(String imageUri) {
        this.imageUri = imageUri;
    }
}

测试


import com.shior.demoshior.config.SystemParams;
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.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class TestConfig {
    @Autowired
    SystemParams systemParams;
    @Test
    public void testParam(){
        System.out.println(systemParams.getImageUri());
    }
}
收藏00

登录 后评论。没有帐号? 注册 一个。