Java java지도 시간 SpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?

SpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?

May 11, 2023 am 09:34 AM
springboot yml

yml 파일에 사전 데이터를 구성하고, yml을 로드하여 Map에 데이터를 로드합니다.

Spring Boot의 yml 구성은 다른 yml의 구성을 참조합니다. # 구성 파일 디렉터리(예: 리소스)에 새 application-xxx를 만듭니다. yml 파일은 application으로 시작해야 합니다. 여러 파일은 ","로 구분되며 프로젝트 구조를 줄 바꿈할 수 없습니다. file application-xxx

必须以application开头的yml文件, 多个文件用 "," 号分隔,不能换行

项目结构文件

SpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?

application.yml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

server:

  port: 8088

  application:

    name: VipSoft Env Demo

 

 

spring:

  profiles:

    include:

      dic      # 在配置文件目录(如:resources)下新建application-xxx 开头的yml文件, 多个文件用 "," 号分隔,不能换行

 

#性别字典

user-gender:

  0: 未知

  1: 男

  2: 女

로그인 후 복사

application-dic.yml

将字典独立到单独的yml文件中

1

2

3

4

#支付方式

pay-type:

  1: 微信支付

  2: 货到付款

로그인 후 복사

resources 目录下,创建META-INF目录,创建 spring.factories

SpringBoot는 어떻게 YML 파일에 사전 데이터를 로드합니까?

application .yml

1

2

# Environment Post Processor

org.springframework.boot.env.EnvironmentPostProcessor=com.vipsoft.web.utils.ConfigUtil

로그인 후 복사

application-dic.yml

사전을 별도의 yml 파일로 분리하세요

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

package com.vipsoft.web.utils;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.context.properties.bind.BindResult;

import org.springframework.boot.context.properties.bind.Binder;

import org.springframework.boot.env.EnvironmentPostProcessor;

import org.springframework.core.env.ConfigurableEnvironment;

import org.springframework.core.env.PropertySource;

import org.springframework.util.Assert;

 

public class ConfigUtil implements EnvironmentPostProcessor {

 

    private static Binder binder;

 

    private static ConfigurableEnvironment environment;

 

    public static String getString(String key) {

        Assert.notNull(environment, "environment 还未初始化!");

        return environment.getProperty(key, String.class, "");

    }

 

    public static <T> T bindProperties(String prefix, Class<T> clazz) {

        Assert.notNull(prefix, "prefix 不能为空");

        Assert.notNull(clazz, "class 不能为空");

        BindResult<T> result = ConfigUtil.binder.bind(prefix, clazz);

        return result.isBound() ? result.get() : null;

    }

 

    /**

    * 通过 META-INF/spring.factories,触发该方法的执行,进行环境变量的加载

    */

    @Override

    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        for (PropertySource<?> propertySource : environment.getPropertySources()) {

            if (propertySource.getName().equals("refreshArgs")) {

                return;

            }

        }

        ConfigUtil.environment = environment;

        ConfigUtil.binder = Binder.get(environment);

    }

}

로그인 후 복사

resources 디렉터리에서 META-INF 디렉터리를 생성하세요. spring.factories 파일을 생성합니다.

Spring 팩토리는 Java SPI와 유사한 메커니즘으로 META-INF/spring.factories 파일에서 인터페이스의 구현 클래스 이름을 구성한 다음 이를 읽습니다. 프로그램 이러한 구성 파일은 인스턴스화됩니다. 내용은 다음과 같습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

package com.vipsoft.web.vo;

 

 

public class DictVO implements java.io.Serializable {

    private static final long serialVersionUID = 379963436836338904L;

    /**

     * 字典类型

     */

    private String type;

    /**

     * 字典编码

     */

    private String code;

    /**

     * 字典值

     */

    private String value;

 

    public DictVO(String code, String value) {

        this.code = code;

        this.value = value;

    }

 

    public String getType() {

        return type;

    }

 

    public void setType(String type) {

        this.type = type;

    }

 

    public String getCode() {

        return code;

    }

 

    public void setCode(String code) {

        this.code = code;

    }

 

    public String getValue() {

        return value;

    }

 

    public void setValue(String value) {

        this.value = value;

    }

}

로그인 후 복사

ConfigUtilSpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

package com.vipsoft.web.controller;

 

import com.vipsoft.web.utils.ConfigUtil;

import com.vipsoft.web.vo.DictVO;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;

 

import java.util.ArrayList;

import java.util.LinkedHashMap;

import java.util.List;

 

 

@RestController

public class DefaultController {

    @GetMapping(value = "/")

    public String login() {

        return "VipSoft Demo !!!";

    }

 

    @GetMapping("/list/{type}")

    public List<DictVO> listDic(@PathVariable("type") String type) {

        LinkedHashMap dict = ConfigUtil.bindProperties(type.replaceAll("_", "-"), LinkedHashMap.class);

        List<DictVO> list = new ArrayList<>();

        if (dict == null || dict.isEmpty()) {

            return list;

        }

        dict.forEach((key, value) -> list.add(new DictVO(key.toString(), value.toString())));

        return list;

    }

}

로그인 후 복사

DictVo

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

package com.vipsoft.web;

 

import com.vipsoft.web.controller.DefaultController;

import com.vipsoft.web.utils.ConfigUtil;

import com.vipsoft.web.vo.DictVO;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

 

import java.util.List;

 

@SpringBootTest

public class DicTest {

    @Autowired

    DefaultController defaultController;

 

    @Test

    public void DicListTest() throws Exception {

        List<DictVO> pay_type = defaultController.listDic("pay-type");

        pay_type.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue()));

 

 

        List<DictVO> user_gender = defaultController.listDic("user-gender");

        user_gender.forEach(p -> System.out.println(p.getCode() + " => " + p.getValue()));

    }

 

 

    @Test

    public void getString() throws Exception {

        String includeYml = ConfigUtil.getString("spring.profiles.include");

        System.out.println("application 引用了配置文件 =》 " + includeYml);

    }

}

로그인 후 복사
DefaultControllerrrreee

실행 효과SpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?

🎜🎜🎜🎜🎜유닛 테스트🎜🎜rrreee 🎜 🎜🎜

위 내용은 SpringBoot는 yml 파일에서 사전 데이터를 어떻게 로드합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Springboot가 Jasypt를 통합하여 구성 파일 암호화를 구현하는 방법 Springboot가 Jasypt를 통합하여 구성 파일 암호화를 구현하는 방법 Jun 01, 2023 am 08:55 AM

Springboot가 Jasypt를 통합하여 구성 파일 암호화를 구현하는 방법

SpringBoot가 Redisson을 통합하여 지연 대기열을 구현하는 방법 SpringBoot가 Redisson을 통합하여 지연 대기열을 구현하는 방법 May 30, 2023 pm 02:40 PM

SpringBoot가 Redisson을 통합하여 지연 대기열을 구현하는 방법

Redis를 사용하여 SpringBoot에서 분산 잠금을 구현하는 방법 Redis를 사용하여 SpringBoot에서 분산 잠금을 구현하는 방법 Jun 03, 2023 am 08:16 AM

Redis를 사용하여 SpringBoot에서 분산 잠금을 구현하는 방법

springboot가 파일을 jar 패키지로 읽은 후 파일에 액세스할 수 없는 문제를 해결하는 방법 springboot가 파일을 jar 패키지로 읽은 후 파일에 액세스할 수 없는 문제를 해결하는 방법 Jun 03, 2023 pm 04:38 PM

springboot가 파일을 jar 패키지로 읽은 후 파일에 액세스할 수 없는 문제를 해결하는 방법

SpringBoot와 SpringMVC의 비교 및 ​​차이점 분석 SpringBoot와 SpringMVC의 비교 및 ​​차이점 분석 Dec 29, 2023 am 11:02 AM

SpringBoot와 SpringMVC의 비교 및 ​​차이점 분석

SpringBoot가 Redis를 사용자 정의하여 캐시 직렬화를 구현하는 방법 SpringBoot가 Redis를 사용자 정의하여 캐시 직렬화를 구현하는 방법 Jun 03, 2023 am 11:32 AM

SpringBoot가 Redis를 사용자 정의하여 캐시 직렬화를 구현하는 방법

springboot에서 application.yml의 값을 얻는 방법 springboot에서 application.yml의 값을 얻는 방법 Jun 03, 2023 pm 06:43 PM

springboot에서 application.yml의 값을 얻는 방법

여러 테이블을 추가하기 위해 SQL 문을 사용하지 않고 Springboot+Mybatis-plus를 구현하는 방법 여러 테이블을 추가하기 위해 SQL 문을 사용하지 않고 Springboot+Mybatis-plus를 구현하는 방법 Jun 02, 2023 am 11:07 AM

여러 테이블을 추가하기 위해 SQL 문을 사용하지 않고 Springboot+Mybatis-plus를 구현하는 방법

See all articles