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

 

转载于:https://www.cnblogs.com/zuoxh/p/9805284.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值