zoukankan      html  css  js  c++  java
  • Spring Boot 7:配置文件信息读取

    配置信息的读取

    在application.yml中配置

    author:
        name: YangXuyue
        age: 24
        address: Hangzhou,China
    @Component
    public class Author {
    
        @Value("${author.name}")
        private String name;
    
        @Value("${author.age}")
        private Integer age;
    
        @Value("${author.address}")
        private String address;
    
    }

    application.yml配置另一种方式

    author:
        name: YangXuyue
        age: 24
        address: Hangzhou,China
    @Component
    @ConfigurationProperties(prefix = "author")
    public class Author{
    
        private String name;
    
        private Integer age;
    
        private String address;
    
    }

    使用 @ConfigurationProperties 注解并使用 prefix 指定一个前缀,那么该类中的属性名就是配置中去掉前缀后的名字,一一对应即可。即:前缀名 + 属性名就是配置文件中定义的 key。
    同时,该类上面需要加上 @Component 注解,把该类作为组件放到 Spring 容器中,让 Spring 去管理,我们使用的时候直接注入即可。

    @ConfigurationProperties 依赖

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

    在.properties中配置

    author.properties

    author.name = YangXuyue
    author.age = 24
    author.address = Hangzhou,China
    author.lover = Ning
    @Component
    // prefix用来选择属性的前缀
    @ConfigurationProperties(prefix = "author")
    // 配置文件路径
    @PropertySource("classpath:config/author.properties")
    public class Author {
        /*
        如果配置在application.properties中,
        变量的值可以采用@Value("${...}")注解进行获取
         */
        private String name;
        private String address;
        private Integer age;
        private String lover;
    }

    指定项目配置文件

    application.yml

    spring:
        # 环境 dev:开发环境|test:测试环境|prod:生产环境
        profiles:
            active: dev

    application-dev.yml

    server:
        tomcat:
            uri-encoding: utf-8
            max-threads: 1000
            min-spare-threads: 30
            port: 1003
            context-path: /yang

    application-prod.yml

    ...

    application-test.yml

    ...

  • 相关阅读:
    A Node Influence Based Label Propagation Algorithm for Community detection in networks 文章算法实现的疑问
    Fast Newman-FN算法以及模块度定义介绍
    Label Propagation Algorithm LPA 标签传播算法解析及matlab代码实现
    设计一个smartnic
    Intel GEN11 GPU
    Intel GEN9 GPU
    Shared Virtual Memory (SVM) Functions
    connect via ssh to virtualbox guest vm without knowing ip address
    smartnic
    技术精品翻译
  • 原文地址:https://www.cnblogs.com/yang21/p/9977296.html
Copyright © 2011-2022 走看看