读取.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;

 

posted @ 2018-10-17 17:01  帅的很耗cpu  阅读(255)  评论(0编辑  收藏  举报