springboot项目读取 .yml 配置文件,springboot中static静态变量读取yml文件配置

application.yml

# 系统配置
server:
  # 服务器的HTTP端口,默认为8080
  port: 9006
  servlet:
    # 应用的访问路径
    context-path: /

# 自定义配置
url:
  ip: 127.0.0.1
  port: 8080
  protocol: http
configs:
  str: test
  map:
    id: 0125
    name: name
    code: code
  list:
    - testStr1
    - testStr2
    - testStr3
  listMap:
    - id: 10235
      name: name1
    - id: 20357
      name: name2
    - id: 30568
      name: name3
View Code

方法一:

使用 @ConfigurationProperties(prefix = "configs") 可以以string,map,list等数据类型返回配置信息:

SysConfigs.java:

package com.example.demo.common;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

@Data
@ToString
@Component
@ConfigurationProperties(prefix = "configs")
public class SysConfigs {

    /** String类型 **/
    private String str;

    /** map类型 **/
    private Map<String, String> map;

    /** list **/
    private List<String> list;

    /** list **/
    private List<Map<String, String>> listMap;
}
View Code

 

方法二:

在使用 @Component,@service,@RestController,@Controller 等注解的java类中的属性上使用@Value("${url.ip}")进行配置读取:

ConfigsController.java:

package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.SysConfigs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("configs")
public class ConfigsController {

    @Value("${url.ip}")
    private String ip;

    @Value("${url.port}")
    private String port;

    @Value("${url.protocol}")
    private String protocol;

    @Autowired
    private SysConfigs sysConfigs;

    @GetMapping("get-all")
    public ResponseEntity<JSONObject> getAll() {
        JSONObject json = new JSONObject();
        json.put("str", sysConfigs.getStr());
        json.put("map", sysConfigs.getMap());
        json.put("list", sysConfigs.getList());
        json.put("listMap", sysConfigs.getListMap());
        json.put("url", protocol + "://" + ip + ":" + port);
        return ResponseEntity.ok().body(json);
    }
}
View Code

最终效果:

 

static静态变量读取yml文件

application.yml:

server:
  # 访问相关配置
  port: 9090
  tomcat:
    uri-encoding: utf-8
  servlet:
    context-path: /

spring:
  # 数据库配置
  datasource:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    username: username
    password: password
  mvc:
    # spring boot 视图配置
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
    # 静态文件访问配置
#    static-path-pattern: /static/**
#  web:
#    resources:
#      static-locations:
#      - classpath:/static/
#      - classpath:/templates/

mybatis:
  mapper-locations: classpath:mybatis/mappers/*Mapper.xml
  type-aliases-package: com.sinosoft.tp.system.entity
  config-location: classpath:mybatis/mybatis-config.xml

configs:
  page:
    show-count: 10
    pd:
      test1: test1
      test2: 2
      test3: 5.9
  test:
    name: name1
    age: 13
    height: 1.8
    likes:
      - 篮球
      - 足球
      - 橄榄球
  likes2:
    - 网球
    - 棒球
    - 羽毛球


debug: true
View Code

ConstConfigs.java

package com.sinosoft.tp.constants;

import com.sinosoft.tp.utils.Page;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

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

@Data
@Component
@ConfigurationProperties(prefix = "configs")
public class ConstConfigs {

    // 静态 实体 映射
    public static Page page;
    // 静态 单值 字符串 映射
    public static String name;
    // 静态 单值 数字 映射
    public static Integer pageSize;
    // 静态 集合 映射
    public static List<String> likes2;
    // 静态 map 映射
    public static Map<String, Object> test;

    public void setPage(Page page) {
        ConstConfigs.page = page;
    }

    @Value("${configs.page.show-count}") // 使用 @Value 只能对单一值进行取值,例如:String,Integer等,集合或map等类型的会抛异常
    public void setPageSize(Integer pageSize) {
        ConstConfigs.pageSize = pageSize;
    }

    @Value("${configs.test.name}") // 使用 @Value 只能对单一值进行取值,例如:String,Integer等,集合或map等类型的会抛异常
    public void setName(String name) {
        ConstConfigs.name = name;
    }

    public void setLikes2(List<String> likes2) {
        ConstConfigs.likes2 = likes2;
    }

    public void setTest(Map<String, Object> test) {
        ConstConfigs.test = test;
    }
}
View Code

TestController.java

package com.sinosoft.tp.system.controller;

import com.sinosoft.tp.base.BaseController;
import com.sinosoft.tp.base.Result;
import com.sinosoft.tp.constants.ConstConfigs;
import com.sinosoft.tp.utils.Page;
import com.sinosoft.tp.utils.RSAUtil;
import com.sinosoft.tp.utils.Results;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Slf4j
@Controller
public class TestController extends BaseController {

    @ResponseBody
    @RequestMapping("test")
    public Result test() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("str-name", ConstConfigs.name);
        jsonObject.put("int-pageSize", ConstConfigs.pageSize);
        jsonObject.put("list-likes2", ConstConfigs.likes2);
        jsonObject.put("map-test", ConstConfigs.test);
        jsonObject.put("entity-page", ConstConfigs.page);
        return Results.successWithData(jsonObject);
    }

}
View Code

请求 http://127.0.0.1:9090/test 最终效果:

 

 细心的你可能会发现,在SysConfigs.java中多了两个注解 @Data  @ToString,而且并没有写getter和setter方法,这是因为在idea中安装了lombok,只需要关心有哪些属性就行,可以在开发中省好多事儿。

 

每天进步一点点,点滴记录,积少成多。

以此做个记录,

如有不足之处还望多多留言指教!

 

posted @ 2021-07-05 16:45  金刀3691  阅读(1324)  评论(0编辑  收藏  举报