Article Directory
Application scenario:
There are many things that need to be read in java, but they may be modified, such as jdbc connection configuration, loading configuration files (may change the path or class name), etc., if they are directly written in java, it will After being compiled into a class file for reading, we should try our best to not even modify the java file, which can be achieved by configuring the properties file.
1. Method to read properties file in Java file
step:
- Create an object of Properties
- Obtain the
InputStream
stream object of the properties file through the class loaderXxxClass.class.getClassLoader().getResourceAsStream("xx.properties");
load(InputStream)
Load the property file by calling the method of the Properties object , the parameter is theInputStream
stream object of the properties filegetProperty(key)
Read the value of the property file through the method of the Properties object , and the parameter is the key of the properties file.
//从配置文件中取数据 .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"));
Set the properties file info.properties
applicationConfig = applicationContext.xml
PersonServiceImpl = personServiceImpl
Run result, read successfully
applicationContext.xml
personServiceImpl
2. Read properties file in xml
By context:property-placeholder
tags, readers
<context:property-placeholder location="classpath:db.properties" />
The location is the directory of the compiled class file. Because my db.properties
property file is placed in the resources
directory, it is directly in the corresponding classes
directory and can be viewed through the target directory.