zoukankan      html  css  js  c++  java
  • 读取.Properties文件以及Spring注解读取文件内容

     1 public class Main {
     2 
     3     public static void main(String[] args) throws IOException {
     4         //创建Properties对象
     5         Properties prop = new Properties();
     6         //读取classPath中的properties文件
     7         prop.load(Main.class.getClassLoader().getResourceAsStream("bean.properties"));
     8         //根据键取出值
     9         String className = prop.getProperty("className");
    10         System.out.println(className);
    11         
    12     }
    13 }
      输出className对应的值

    封装的工具类

     1 public class PropertyUtil {
     2 
     3     private static Properties prop = new Properties();
     4 
     5     static {
     6         try {
     7             prop.load(PropertyUtil.class.getClassLoader().getResourceAsStream("calculator.properties"));
     8         } catch (IOException e) {
     9             throw new RuntimeException(e.getMessage());
    10         }
    11     }
    12 
    13     /**
    14      * 根据Name获取Property
    15      * @param name
    16      * @return
    17      */
    18     public static String getProperty(String name) {
    19         return prop.getProperty(name);
    20     }
    21 
    22     /**
    23      * 获取所有的Property
    24      * @return
    25      */
    26     public static List<String> getBeanFactoryClass() {
    27         List<String> list = new ArrayList<>();
    28         Set<String> keys = prop.stringPropertyNames();
    29         for (String key : keys) {
    30             list.add(prop.getProperty(key));
    31         }
    32         return list;
    33     }
    34 }

    转载地址:https://www.cnblogs.com/hhmm99/p/9803119.html

    内容很简单,但是感觉很有用

    下面是Spring的通过@Value注解读取.properties配置内容

    在Spring-dao.xml的配置文件中配置

     1 <util:properties id="Prop" location="classpath:db.properties" /> 

    内容

    1 salt=helloworld

    使用注解获取配置内容

    1 //从db.properties文件中获取的值
    2 @Value("#{Prop.salt}")
    3 private String salt;
  • 相关阅读:
    微软职位内部推荐-Senior SDE
    在使用Fake framework的时候,为什么有一些函数没有生产mock呢?
    Call Azure Queue get "The remote server returned an error: (400) Bad Request."
    技术分享
    IT牛人博客
    Spring-data-redis操作redis cluster
    Spring对Hibernate事务管理【转】
    Hibernate事务管理
    Redis与Memcached对比
    LockSupport的park和unpark
  • 原文地址:https://www.cnblogs.com/zuoxh/p/9805284.html
Copyright © 2011-2022 走看看