优化(防止写死),properties文件的读取。通过properties属性文件配置键值对,实现可修改优化。

应用场景:
  在java中有很多东西是需要读取的,但是又可能进行修改,比如jdbc连接配置,加载配置文件(可能更改路径或者类名)等等,如果直接写死在java中,它会经过编译成class文件读取,我们要尽量的甚至不要对java文件进行修改,就可以通过配置properties属性文件来实现。

1. Java文件中读取properties属性文件的方法

步骤:

  1. 创建Properties的对象
  2. 通过类加载器获取properties属性文件的InputStream流对象 XxxClass.class.getClassLoader().getResourceAsStream("xx.properties");
  3. 通过调用Properties对象的load(InputStream)方法加载属性文件,参数是properties属性文件的InputStream流对象
  4. 通过Properties的对象的getProperty(key)方法读取属性文件的值,参数是properties属性文件的键key。
    //从配置文件中取数据 .properties  Properties
        Properties p = new Properties();
        InputStream is = LoginServlet.class.getClassLoader().getResourceAsStream("info.properties");
        p.load(is);
        
        System.out.println(p.getProperty("applicationConfig"));
        System.out.println(p.getProperty("PersonServiceImpl"));
        //调用登录方法p.getProperty("config")获取属性文件中的config键的值 也就是核心配置文件的路径
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext(p.getProperty("config"));
        IPersonService personService = (IPersonService) context.getBean(p.getProperty("serviceId"));

设置属性文件info.properties

applicationConfig = applicationContext.xml
PersonServiceImpl = personServiceImpl

运行结果,读取成功

applicationContext.xml
personServiceImpl

2. xml中读取properties属性文件

通过 context:property-placeholder标签,读取

 <context:property-placeholder location="classpath:db.properties" />

location是编译后的class文件的目录,因为我的db.properties属性文件放在resources目录下,所以它就直接在对应的classes目录下,可以通过target目录查看。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40542534/article/details/108987881