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;
    }
    

      

  • 相关阅读:
    深圳和上海
    肖舸的“畅销门”和“卓越门”
    一件小事引发的辞职——团队里的Y君
    同洲、宇龙手机源代码之争
    《过得去》
    评肖舸之《0bug一书给谁带来了奶酪?》
    《观止》点滴
    webgame 地图加载(论坛摘录)
    分块加载(转)
    45度游戏的另类深度排序(copyPixels)
  • 原文地址:https://www.cnblogs.com/h-z-y/p/14601577.html
Copyright © 2011-2022 走看看