zoukankan      html  css  js  c++  java
  • SpringBoot自定义参数(6)

    一、使用yml配置文件

     第一种方式就是把自定义参数配置在yml配置文件中。

    例如,在application.yml中加入如下配置。

    #自定义参数
    define:
      userinfo:
        username: hzy
      department:
        name: 研发部门
    

    (1)采用传统的@Value注解注入。注意写法  @Value( "$ {   }" )

     
    @Component
    @Data
    public class Department {
     
        @Value("${define.department.name}")
        private String name;
    }
    

    (2)采用SpringBoot的@ConfigurationProperties注解注入。指明前缀即可。

    @ConfigurationProperties(prefix = "define.userinfo")
    @Component
    @Data
    public class UserInfo {
     
        private String username;
     
        private int age;
     
        private String position;
    

    二、使用Properties配置文件

    新建一个配置文件,例如db.properties文件。

    database.name = ORACLE
    database.version = 11
    

    SpringBoot十分贴心的提供了一个@PropertySource注解。只需要指明文件位置即可。

    这也分两种注入方式,第一种就是使用@ConfigurationProperties,指明前缀就能省去使用@Value注解。

    @PropertySource(value = "classpath:config/db.properties")
    @ConfigurationProperties(prefix = "database")
    @Component
    @Data
    public class Database {
     
        private String name;
     
        private String version;
    }
    

    第二种就是不用@ConfigurationProperties指明前缀,直接使用@Value注解,配上全名。

    @PropertySource(value = "classpath:config/db.properties")
    @Component
    @Data
    public class DatabaseCopy {
     
        @Value("${database.name}")
        private String name;
     
        @Value("${database.version}")
        private String version;
    }
    

      

  • 相关阅读:
    SQL语句中的左连接、右连接、内连接的理解心得
    MySQL+Java使用心得(1)
    【转】国内常见WEB安全扫描产品概述
    [C puzzle book] operators
    【Python】Symbol Review
    A function for new storage space of string
    【SRX】折腾了半天终于我的那对SRX210 升级到了 12.1R1.9
    [C puzzle book] Control Flow
    [C puzzle book] types
    荷兰TAC的需求
  • 原文地址:https://www.cnblogs.com/h-z-y/p/14601577.html
Copyright © 2011-2022 走看看