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;

          }

        }

  • 相关阅读:
    c#正则表达式应用实例
    C# 中堆栈,堆,值类型,引用类型的理解 (摘抄)
    c#用正则表达式获得指定开始和结束字符串中间的一段文本
    asp.net c#截取指定字符串函数
    <收藏>提高Web性能的14条法则(详细版)
    利用Anthem.net 实现前台javascript调用服务器端c#函数 及流程分析
    Anthem.net
    jQuery animate(滑块滑动)
    .NET使用母版页后,控件名称自动生成导致js无法正常操作.net控件的问题
    Cocos2dx跨平台Android环境配置
  • 原文地址:https://www.cnblogs.com/hope-xu/p/10744634.html
Copyright © 2011-2022 走看看