Read the properties file in Java

Source: Internet
Author: User
Tags access properties

Five ways for you to read the properties file in Java

I. BACKGROUND

Recently, in the process of project development, encountered the need to define some custom variables in the properties file, for the Java program to read dynamically, modify the variables, no longer need to modify the code of the problem. Take this opportunity to spring+springmvc+mybatis integrated development of the project through the Java program to read the contents of the properties file in a way to comb and analyze, now and everyone share.

Ii. introduction of the project environment

Spring 4.2.6.RELEASE

Springmvc 4.2.6.RELEASE

Mybatis 3.2.8

Maven 3.3.9

JDK 1.7

Idea 15.04

Three or five ways to implement

Mode 1. Load the contents of the configuration file jdbc.properties via Context:property-placeholder

<context:property-placeholder location= "Classpath:jdbc.properties" ignore-unresolvable= "true"/>

The above configuration is equivalent to the following configuration, which simplifies the following configuration

<bean id= "Propertyconfigurer" class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >   <property name= "Ignoreunresolvableplaceholders" value= "true"/>   <property name= "Locations" >      <list>         <value>classpath:jdbc.properties</value>      </list>    </ Property></bean>

Note: In this way, if you have the following configuration in the Spring-mvc.xml file, you must not be missing the red part below, for its function and principle, see another blog:context: The function and principle analysis of use-default-filters attribute of Component-scan tag

<!--configuration component Scan, only controller annotations--><context:component-scan base-package= "com.hafiz.www" in SPRINGMVC container Use-default-filters= "false" >    <context:include-filter type= "annotation" expression= " Org.springframework.stereotype.Controller "/></context:component-scan>

Mode 2. Injected using annotations, primarily in Java code using annotations to inject the corresponding value values in the properties file

<bean id= "prop" class= "Org.springframework.beans.factory.config.PropertiesFactoryBean" >   <!-- Here is the Propertiesfactorybean class, which also has a locations property, and also receives an array, as above--   <property name= "Locations" >       < array>          <value>classpath:jdbc.properties</value>       </array>   </property> </bean>

Mode 3. Use the util:properties tag to expose the contents of the properties file

<util:properties id= "Propertiesreader" location= "Classpath:jdbc.properties"/>

Note: Using this line of configuration, you need to declare the following red section on the head of the Spring-dao.xml file

<beans xmlns= "Http://www.springframework.org/schema/beans"       xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "       xmlns:context=" Http://www.springframework.org/schema/context "       xmlns:util="/http/ Www.springframework.org/schema/util "       xsi:schemalocation=" Http://www.springframework.org/schema/beans        Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd        http://www.springframework.org/schema/ Context         Http://www.springframework.org/schema/context/spring-context-3.2.xsd        
Http://www.springframework.org/schema/util/spring-util.xsd ">

Mode 4. Expose properties to custom subclasses for use in a program by Propertyplaceholderconfigurer when loading the context

<bean id= "Propertyconfigurer" class= "Com.hafiz.www.util.PropertyConfigurer" >   <property name= " Ignoreunresolvableplaceholders "value=" true "/>   <property name=" Ignoreresourcenotfound "value=" true "/ >   <property name= "Locations" >       <list>          <value>classpath:jdbc.properties</ value>       </list>   </property></bean>

The declaration of the custom class Propertyconfigurer is as follows:

Package Com.hafiz.www.util;import Org.springframework.beans.beansexception;import Org.springframework.beans.factory.config.configurablelistablebeanfactory;import Org.springframework.beans.factory.config.propertyplaceholderconfigurer;import java.util.Properties;/** * Desc: Properties Config file read class * Created by Hafiz.zhang on 2016/9/14.       */public class Propertyconfigurer extends Propertyplaceholderconfigurer {private Properties props; Access properties configuration file Key-value result @Override protected void processproperties (Configurablelistablebeanfactory beanfactor Ytoprocess, Properties props) throws Beansexception {super.processproperties (beanfactor        Ytoprocess, props);    This.props = props;    public string GetProperty (string key) {return This.props.getProperty (key);     public string GetProperty (string key, String defaultvalue) {return This.props.getProperty (key, DefaultValue); } Public Object SetProperty (string key, String VALue) {return This.props.setProperty (key, value); }}

How to use: Use @autowired annotation injection in the class you need to use.

Way 5. Customize the tool class Propertyutil and read the properties file contents in the static static code block of the class to be saved in the static property for other programs to use

Package Com.hafiz.www.util;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import java.io.*;import java.util.properties;/** * desc:properties File Get tool class * Created by Hafiz.zhang on 2016/9/15.    */public class Propertyutil {private static final Logger Logger = Loggerfactory.getlogger (Propertyutil.class);    private static Properties props;    static{Loadprops ();        } synchronized static private void Loadprops () {logger.info ("Start loading properties File contents ...");        props = new Properties ();        InputStream in = null; try {
<!--first, get the properties file stream through the ClassLoader--in = PropertyUtil.class.getClassLoader (). getResourceAsStream ("Jdbc.pro Perties ");
       <!--second, get Properties file stream by Class--//in = PropertyUtil.class.getResourceAsStream ("/jdbc.properties") ; Props.load (in); } catch (FileNotFoundException e) {logger.error ("Jdbc.properties File not Found"); } catch (IOException e) {logger.error ("appears IOException"); } finally {try {if (null! = in) {in.close (); }} catch (IOException e) {logger.error ("Jdbc.properties file stream close exception"); }} logger.info ("Load Properties file contents complete ..."); Logger.info ("Properties File contents:" + props); public static string GetProperty (string key) {if (null = = props) {loadprops (); } return Props.getproperty (key); public static string GetProperty (string key, String defaultvalue) {if (null = = props) {Loadprops () ; } return Props.getproperty (key, DefaultValue); }}

Description: In this case, when the class is loaded, it automatically reads the configuration file contents of the specified location and saves it to a static property, which is efficient and convenient, once loaded, and can be used multiple times.

Iv. matters needing attention and suggestions

The first three methods are more rigid, and if you want to use them in a bean with @controller annotations, you need to declare them in the SPRINGMVC configuration file Spring-mvc.xml If you want to have @service, @ Respository are used in beans other than @controller annotations, you need to declare them in Spring.xml in the spring configuration file. Reasons See another blog:Spring and Springmvc a glimpse of the relationship between the parent and the child containers

I personally recommend the fourth and fifth configuration, fifth is the best, it even the tool class objects do not need to inject, directly call the static method to obtain, and only one load, high efficiency. And the first three ways are not very flexible, you need to modify the @value key value.

V. Test validation is available

1. First we create Propertiesservice

Package com.hafiz.www.service;/** * Desc:java program Gets the properties file contents of service * Created by Hafiz.zhang on 2016/9/16.  */public interface Propertiesservice {/** * First implementation gets the value of the specified key in the properties file * * @return */String    Getproperybyfirstway ();    /** * The second implementation gets the value of the specified key in the properties file * * @return */String getproperybysecondway ();    /** * The third implementation method gets the value of the specified key in the properties file * * @return */String getproperybythirdway (); /** * Fourth Implementation method gets the value of the specified key in the properties file * * @param key * * @return */String Getproperybyfourth    The (String key);     /** * Fourth Implementation method gets the value of the specified key in the properties file * * @param key * * @param defaultvalue * * @return    */String Getproperybyfourthway (String key, string defaultvalue); /** * Fifth implementation method Gets the value of the specified key in the properties file * * @param key * * @return */String GETPROPERYBYFIFTHW    Ay (String key); /** * Fifth implementation method Gets the value of the specified key in the properties file    * * @param key * * @param defaultvalue * * @return * * * string getproperybyfifthway (String ke Y, String defaultvalue);}

2. Create an implementation class Propertiesserviceimpl

Package Com.hafiz.www.service.impl;import Com.hafiz.www.service.propertiesservice;import Com.hafiz.www.util.propertyconfigurer;import Com.hafiz.www.util.propertyutil;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.value;import org.springframework.stereotype.service;/** * Desc: Java program gets the implementation class of the service for the properties file contents * Created by Hafiz.zhang on 2016/9/16. */@Servicepublic class Propertiesserviceimpl implements Propertiesservice {@Value ("${test}") Private String Testdat    Abyfirst;    @Value ("#{prop.test}") Private String Testdatabysecond;    @Value ("#{propertiesreader[test]}") Private String Testdatabythird;    @Autowired private Propertyconfigurer pc;    @Override public String Getproperybyfirstway () {return testdatabyfirst;    } @Override Public String Getproperybysecondway () {return testdatabysecond; } @Override Public String Getproperybythirdway () {return TestdatabythirD    } @Override public string Getproperybyfourthway (string key) {return Pc.getproperty (key);  } @Override public string Getproperybyfourthway (string key, String defaultvalue) {return Pc.getproperty (key,    DefaultValue);    } @Override public string Getproperybyfifthway (string key) {return propertyutil.getpropery (key); } @Override public string Getproperybyfifthway (string key, String defaultvalue) {return Propertyutil.getprop    Erty (key, DefaultValue); }}

3. Controller class Propertycontroller

Package Com.hafiz.www.controller;import Com.hafiz.www.service.propertiesservice;import Com.hafiz.www.util.propertyutil;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import org.springframework.web.bind.annotation.responsebody;/** * desc:properties Test controller * Created by Hafiz.zhang on 2016/9/16.    */@Controller @requestmapping ("/prop") public class Propertycontroller {@Autowired private propertiesservice PS; @RequestMapping (value = "/way/first", method = Requestmethod.get) @ResponseBody public String Getpropertybyfirstway (    ) {return ps.getproperybyfirstway (); } @RequestMapping (value = "/way/second", method = Requestmethod.get) @ResponseBody public String getpropertybysec Ondway () {return Ps.getproperybysecondway (); } @RequestMapping (value = "/way/third", method = Requestmethod.get) @ResponseBody public String Getpropertybythir    Dway () {return ps.getproperybythirdway (); } @RequestMapping (value = "/way/fourth/{key}", method = Requestmethod.get) @ResponseBody public String Getpropert    Ybyfourthway (@PathVariable ("key") String key) {return Ps.getproperybyfourthway (key, "DefaultValue"); } @RequestMapping (value = "/way/fifth/{key}", method = Requestmethod.get) @ResponseBody public String GetProperty    Byfifthway (@PathVariable ("key") String key) {return Propertyutil.getproperty (key, "DefaultValue"); }}

4.jdbc.properties file

jdbc.driver=com.mysql.jdbc.driverjdbc.url=jdbc:mysql://192.168.1.196:3306/dev?useunicode=true& Characterencoding=utf-8jdbc.username=rootjdbc.password=123456jdbc.maxactive=200jdbc.minidle=5jdbc.initialsize= 1jdbc.maxwait=60000jdbc.timebetweenevictionrunsmillis=60000jdbc.minevictableidletimemillis= 300000jdbc.validationquery=select 1 from t_userjdbc.testwhileidle=truejdbc.testonreturn= Falsejdbc.poolpreparedstatements=truejdbc.maxpoolpreparedstatementperconnectionsize=20jdbc.filters=stat#test Datatest=com.hafiz.www

5. Project Results diagram

  

6. Project GitHub Address

The Propertiesconfigurer branch under the Https://github.com/hafizzhang/SSM/branches page.

7. Test results

The first way

  

The second way

  

The Third Way

  

Fourth Way

  

Fifth Way

  

Vi. Summary

Through this combing and testing, we understand the parent-child container relationships of spring and SPRINGMVC, as well as the role and rationale of the use-default-filters attributes that are most easily overlooked when Context:component-scan tag packet scanning. Be able to better locate and quickly solve the problems you encounter again. In short, very good ~ ~ ~

--------------------------------------------------------------------------------------------------------------- ---------------------------------

Transferred from: http://www.cnblogs.com/hafiz/p/5876243.html

Read the properties file in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.