zoukankan      html  css  js  c++  java
  • java 加载并读取Properties 文件

    1 .系统自带的application.properties  (以下代码仅供参考,不能粘贴复制)

      假设application.properties文件有下面两个值:

          come.test.name = chen

          come.test.age = 18

          come.test.phone = 18795812345

      直接在类中的成员变量上添加注解@Value("${ }"),如下

         public class Test(){

          @Value("${come.test.name}")

           public  String name;

          @Value("${come.test.age}")

           public  String age;   

          @Value("${come.test.phone}")

           public  String phone;

          public  static  String getProperties(){

            String value = "name"  + name + "age" + age + "phone" + phone;

            return value;

          }

        }

      注意:上面的类Test已经读取加载properties文件,如果你还想在别的类中引用这个Test类。一定在Test类上面加上@Component 

                     @Component

         public class Test(){

          @Value("${come.test.name}")

           public  String name;

          @Value("${come.test.age}")

           public  String age;   

          @Value("${come.test.phone}")

           public  String phone;

          public  static  String getProperties(){

            String value = "name"  + name + "age" + age + "phone" + phone;

            return value;

          }

        }

     Controller层的类引用Test; 

       @RestController

       public class  Demo{

         @Autowired

          Test test;

        public  String getPro(){

            return  test.getProperties();

          }

       }

    2 . 如果你是自定义的properties文件。只需要在Test类加上注解 @PropertySource("classpath:xxx.properties")

        @Component

        @PropertySource("classpath:xxx.properties")

         public class Test(){

          @Value("${come.test.name}")

           public  String name;

          @Value("${come.test.age}")

           public  String age;   

          @Value("${come.test.phone}")

           public  String phone;

          public  static  String getProperties(){

            String value = "name"  + name + "age" + age + "phone" + phone;

            return value;

          }

        }

  • 相关阅读:
    Java接口自动化测试实战001----get、post方法实现与封装
    临近年关,两个磁盘占满引起的服务下线
    Abp小试牛刀之 图片上传
    Abp vNext异常处理的缺陷/改造方案
    Oh my God, Swagger API文档竟然可以这样写?
    【C#】DockPanelSuite 中 DockState.Document 状态下子窗体控件不显示的解决方案
    环境系列——cygwin启动flink
    环境系列——window10环境下编译Flink源码编译
    弱肉强食——《哆啦A梦:大雄的新恐龙》观后感
    bilibili插件推荐
  • 原文地址:https://www.cnblogs.com/hope-xu/p/10744634.html
Copyright © 2011-2022 走看看