To avoid using hardcode in Java programs, we often use some properties files to store some frequently changed data. In the runtime environment, we configure the data to flexibly configure the application. 1. Introduction To avoid using hardcode in Java programs, we often use some properties files to store some frequently changed data. In the runtime environment, we configure the data to flexibly configure the application. Before the emergence of spring, we usually use resource bundle to read properties files. However, in the Spring environment, the problem becomes simpler, we only need to write a very small amount of code to achieve Random Access to the properties file. 2. applicationcontext. xml file configuration Applicationcontext is an extension of beanfactory. It provides all beanfactory functions. applicationcontext allows you to configure and manage resources managed by spring and spring in a fully declared manner. This article provides the following examples:
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype beans public "-// spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd"> <Beans> <Bean id = "configproperties" Class = "org. springframework. Beans. Factory. config. propertiesfactorybean"> <Property name = "location" value = "file: config. properties"/> </Bean> <Bean id = "propertyconfigurer" Class = "org. springframework. Beans. Factory. config. propertyplaceholderconfigurer"> <Property name = "properties" ref = "configproperties"/> </Bean> <Bean id = "tjtaskcode" class = "tjtaskcode"> <Property name = "taskcode" value = "$ {TJ. taskcode}"/> </Bean> </Beans> |
3. configuration of the config. properties File In this example, I provide a pair of simple data for Demonstration: # Transaction journal task Codes TJ. taskcode = 1034,1035, 1037,1038, 1040,1057, 1058,1074 TJ. taskcode is the key, 1034,1035, 1037,1038, 1040,1057, 1058,1074 is the value; 4. Definition of Java Bean Define Java Bean tjtaskcode. Java to store the required values:
Public class tjtaskcode { Private string taskcode; Public void settaskcode (string taskcode ){ This. taskcode = taskcode; } Public String gettaskcode (){ Return this. taskcode; } } |
5. Execution of the test program testaccessproperties. Java
Import org. springframework. Context. applicationcontext; Import org. springframework. Context. Support. classpathxmlapplicationcontext; Import com. TD. CC. Audit. impl. tjtaskcode; Public class testaccessproperties { Public static void main (string [] ARGs ){ Applicationcontext context; Context = new classpathxmlapplicationcontext ("applicationcontext. xml"); tjtaskcode taskcode1 = (tjtaskcode) Context. getbean ("tjtaskcode "); String taskcode2 = taskcode1.gettaskcode (); System. Out. println (taskcode2 ); If (taskcode2.indexof ("1034 ")! =-1 )// { System. Out. println ("Y "); } Else { System. Out. println ("N "); } } } |
|