Optimized (to prevent write death), read the properties file. Configure the key-value pairs through the properties file to achieve modification and optimization.

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:

  1. Create an object of Properties
  2. Obtain the InputStreamstream object of the properties file through the class loaderXxxClass.class.getClassLoader().getResourceAsStream("xx.properties");
  3. load(InputStream)Load the property file by calling the method of the Properties object , the parameter is the InputStreamstream object of the properties file
  4. getProperty(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-placeholdertags, readers

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

The location is the directory of the compiled class file. Because my db.propertiesproperty file is placed in the resourcesdirectory, it is directly in the corresponding classesdirectory and can be viewed through the target directory.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108987881