应用场景:
在java中有很多东西是需要读取的,但是又可能进行修改,比如jdbc连接配置,加载配置文件(可能更改路径或者类名)等等,如果直接写死在java中,它会经过编译成class文件读取,我们要尽量的甚至不要对java文件进行修改,就可以通过配置properties属性文件来实现。
1. Java文件中读取properties属性文件的方法
步骤:
- 创建Properties的对象
- 通过类加载器获取properties属性文件的
InputStream
流对象XxxClass.class.getClassLoader().getResourceAsStream("xx.properties");
- 通过调用Properties对象的
load(InputStream)
方法加载属性文件,参数是properties属性文件的InputStream
流对象 - 通过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目录查看。