The beauty of Simplicity Jodd--props attribute usage

Source: Internet
Author: User
Tags configuration settings eol trims truncated

Prop is a super properties, contains a lot of jdk missing things: utf-8 support, macros, partitions, profiles, full configuration and so on.

Properties are stored in one or more *.props files, and it is open and supports multiple types of resources. More importantly, it is compatible with Java properties.

The goal of props is not to provide a maximum configuration solution, but rather to provide a better choice than Java properties. So if you use the properties in your application, consider using props instead.

Basic Rules

The following is a basic set of rules that describe the props file format. Some of these rules are examples:

UTF8 encoding

By default, the props file is UTF8 encoded, or you can use any other encoding format. Regardless of which encoding format is used, props still uses ISO 8859-1 when loading Java properites.

Remove whitespace characters

The whitespace characters at the beginning of the partition name and the property name are removed, and the property values are stripped of the opening and closing whitespace characters.

Assign value

You can use "=" or ":" To assign a value.

Value Connection

Use "+ =" to concatenate the values of properties with the same name (separated by commas).

Annotations

From the ";" Or "#" begins at the end of the line to annotate.

Escape character

Use "\" as an escape character to escape characters (for example, "\#" stands for the character "#", "\ \" for "\").

Multi-line value (multi-line values)

If "\" is a connector for a row, the next line is still the value of the property.

Special characters

\\uXXXX will be compiled into characters, and the same \t,\r,\f will be compiled as characters.

Multiline value (Multiline values)

Use three quotation marks as a convenient form to define multiple rows of values.

Note: The syntax of a triple quotation mark is a pair of consecutive single or double quotes (usually paired).

Three quotes allow programmers to escape from the mire of quotes and special strings, keeping a small piece of string in the form of what is known as WYSIWYG.

Basic usage

The use of props is very simple. In general, props manages attributes.

    New Props ();    P.load (new File ("Example.props"));    ...     = P.getvalue ("story");

There are several forms of props loading properties: file, input stream, string, attribute properties. The property value is then called by Props's Etvalue method, which typically returns the value of a string.

Partition

partitions and INI files are very similar to partitions. In props, a partition represents only a set of keys with the same prefix, until the end of the partition or the end of the file.

The partition name is [beginning with] ending. The attribute that belongs to the partition is behind the head of the partition. The partition name is added as a prefix to the partition attribute. The partition starts with an empty [] or a new partition or to the end of the file.

Examples are as follows:

[users.data]  = 49.5= 87.7=[]Comment=this is the base property

The following is equivalent to the example above:

Users.data.weight = 49.5= 87.7=Comment=this is the base property

Therefore, the partition can shorten the file, making the file more readable.

Profiles

Typically, an application has a different environment and therefore requires different groups of attributes. For example, a test environment for Web applications, a publishing environment. One way to organize these properties is to define different profiles in which the same keys have different values.

Props supports the profile of a property. The profile is defined within the key name: The profile name is <> wrapped. One can have one or more profile definitions. Similarly, profile can be defined anywhere in the key name, even in the middle of a word, but it is best to put it at the end of the key name.

Properties that do not have a profile are property-based, and if a property that retrieves a specific profile fails, the underlying property is checked.

Profile can look at a "different view" or "snapshot" of the same attribute group. Example:

db.port=3086db.url<develop>=localhostdb.username<develop>=rootdb.url< deploy>=192.168.1.101db.username<deploy>=app2499

In the above example, 3 keys are defined, two keys have two different profiles (Develop/deploy) and no basic values.

As mentioned above, a partition is a prefix definition for a key, and profile can be defined anywhere in the key name, so the partition name can also contain a profile definition, which can be modified as follows:

db.port=3086[db<develop>]url=localhostusername=root  [db<deploy>]URL=192.168.1.101username=app2499

When retrieving the above values, you can specify an active profile:

    String url = props.getvalue ("Db.url", "develop");    String user = Props.getvalue ("Db.username", "develop");

Note: A profile can be defined several times at a time. The order of profile is very important! When a key is defined to more than one active profile, the first value (the value of the first matching profile) is returned.

You can also simply retrieve the base attribute (ignoring profile)-using the Getbasevalue () method. The base attribute does not belong to any profile.

The default Active profile

Typically, only one set of profiles is active in the life cycle of an application. You do not need to pass this active profile every time you call GetValues (). Props supports the external definition of this so-called active profile, which is defined in the props file that loads the properties.

When retrieving properties using GetValue (String), the active profile is the default profile. Active profiles are defined with special attribute keys for @profiles. For example:

key1=hellokey1<one>=hi! @profiles=one

Then the following Java code:

String value = Props.getvalue ("key1");  

The value "hi!" will be returned because the active profile is "one".

Active profiles can also be set through Java code by: setActiveProfiles() .

Internal profile

There is a scenario where two or more profiles share most of the configuration, and only a few attributes are different. To avoid repeating all of the attributes in each profile, you can use internal profiles to define which properties are different. Props first retrieves the key for the internal profile and then retrieves the basic properties, as shown in the following example:

key1<one>=hi!key2<one>=.......key100<one>=...key1<one.two>= hola!

The above example defines two profiles, the first named "One", and contains 100 key-value pairs. The second profile is an internal profile called One.two. It contains a property (Key1)---but all properties of the upper profile are available! What happens when you call the above property using Java code: Props.getvalue ("Key1", "One.two")?

Props will be

Retrieving properties in internal profile named One.two

If not found, props checks the profile:one on the previous layer.

If it is not yet retrieved, there is no more than one level of profile, and props retrieves the basic properties.

Internal profiles can have many layers.

Macro

The biggest advantage of props is that it supports macros. A macro is a reference to some key values that can be used by other keys. The macro is wrapped in {}. Examples are as follows:

key1=Something ${foo}...foo=nice

The value of Key1 is "Something nice". Macros can reference any existing property keys, regardless of where they are defined.

Nested macros are also supported, as shown in the following example:

key1=**${key${key3}}**key3=2key2=foo

The value of Key1 is "**foo**".

Macros and Profiles

Macros are usually parsed using the currently active or provided profile. If the current profile changes, the value of the macro will usually change.

This behavior is controlled by the flag-bit useactiveprofileswhenresolvingmacros. Examples are as follows:

root=/approot<foo>=/foodata.path=${root}/data

What is the value of Data.path when profile is set to active? Because Foo is active, the value of root becomes/foo, so the value of Data.path is/foo/data.

If we close all profiles and use only basic properties, the value of Data.path is/app/data.

You can also display the profile of the Set macro:

root=/approot<foo>=/foodata.path=${root<foo>}/data

In the example above, the macro root will always use Foo profile regardless of the currently selected profile, so the value of Data.path will always be "/foo/data".

Multi-line values

The values of multiple rows can be defined by three quotation marks. The middle is considered a value:

Email.body= '    Hello $n,    welcome! '

Note: The whitespace of multiple lines of value will not be cut short! Therefore, the values in the above example will contain 5 rows.

Traversal and order of keys

The keys in the props are in order! Therefore, you can traverse all the keys in the order of the keys in the properties file. Do not use the following code:

foo.1=value1foo. 2=value2 ...

You can traverse props as follows:

Props Props == P.iterator ();

The order of traversal is consistent with the order of props definitions.

Further, you can filter the retrieval or/and partition traversal by adding profile. You can write this:

    iterator<propsentry> it = p.entries ()            . Section ("One.two")            . Profile ("Prof1", "Prof2 ")            . Iterator ();

The code above simply iterates through the properties of a given partition and given profile.

Because of the introduction of profile, a key can be defined in multiple places in a property file. For example, you can define a specific value for two different profiles. In this case, you will not be able to determine the correct order of the keys: Is it the first retrieved key or the value obtained at its location? You can control it by using Skipduplicatesbyvalue and Skipduplicatesbyposition ().

Copy operator

Suppose you have a certain number of attributes, that is, by default, as with the number of different kinds, examples are as follows:

com.jodd.action1=value1com.jodd.action2=Value2...org.jodd.action1=  Value1org.jodd.action2=value2...net.jodd .... # etc

Props supports you to use the copy operator (<=) to minimize duplicate properties, which can be written as follows:

 [ actions  Span style= "color: #800000; Font-weight:bold; " >]  action1  =value1action2  =value2 ...  org.jodd <  =< Span style= "color: #000000;" > actions  [ com   jodd <  =  actions  [ net.jodd  ]  <  = Actions 

The above example shows three different ways to use the copy operation, with no partitioning, partial partitioning, and full use of partitions. Whichever of these three methods is available, you can choose any one of them.

Note: The copied value is set to a macro, so all of the above copied properties are also equivalent to:

org.jodd.action1=${actions.action1}com.jodd.action1=${actions.action1} ....

Configuration

There are several configuration settings that can be used to fine tune the props:

  New Line Escape value

Specifies a new string when the line end character (EOL) needs to be escaped. The default value is an empty string, so the value of the multiline is concatenated with the value of the single row. If the new line escape value is set to, for example, "\ n", multiple rows of values are saved as multiple rows.

  Truncated left value

Set this value if you need to cut off from the left.

  Truncated right value

Set this value if you need to cut from the right.

New row ignores the preceding blank value

This value is defined when the value is split into multiple rows (to escape EOL) when the primary whitespace value needs to be ignored. The default value is True, so the following multiline property:

key1=line1     line2line3

will be read as Line1line2line3 (connected)

  Skip Empty Properties

Skips the empty attribute's flag bit.

  Duplicate properties of a connection

Once set, the duplicate property keys will not overwrite the old key, but are concatenated and separated by commas.

  Multi-line values

Enabled by default, a more convenient way to write multiple lines of value, in three quotation marks (like Python) to write. All characters in the three quotation marks are considered a value, so the new line does not need to be escaped.

The source code is as follows:

/*** Value that would be inserted if escaping the new line. */    protectedString Escapenewlinevalue =Stringpool.empty; /*** Trims left the value. */    protected BooleanValuetrimleft =true; /*** Trims right the value. */    protected BooleanValuetrimright =true; /*** Defines if starting whitespaces when value was split in the new line * should was ignored or not. */    protected BooleanIgnoreprefixwhitespacesonnewline =true; /*** Defines if multi-line values may is written using triple-quotes * as in Python. */    protected BooleanMultilinevalues =true; /*** Don ' t include empty properties. */    protected BooleanSkipemptyprops =true;

Reference documents:

Http://jodd.org/doc/props.html

The beauty of Simplicity Jodd--props attribute usage

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.