Inject external values

In Spring, the easiest way to handle external values is to declare a property source and retrieve the property through Spring’s Environment.

@Configuration
@PropertySource("classpath:/com.soundsystem.app.properties")
public class Demo{
    @Autowired
    Environment env;
    @Bean
    public A method(a){
        return new B(
        env.getProperty("dise.title"),
        evn.getProperty("dise.artist")); }}Copy the code

In this case, @propertysource references a file in the classpath called app.properties. He would look something like this:

disc.title=XXXXXXX disc.artist=xxxxxxxxxx

The properties file is loaded into Spring’s Environment, where the properties can be retrieved later. A new Demo is also created in the Method method, whose constructor arguments are taken from the properties file, which is implemented with getPeoperty().

Learn more about Spring’s Environment

The getProperty() method of the Environment class has four overloaded variants.

String getProperty(String key)

String getProperty(String key,String defaultValue)

T getProperty(String key,Class type)

T getProperty(String key,Class type,T defaultValue)

The first two getProperty() methods both return a String value.

The following two do not treat all return values as strings.

DefaultValue represents the value written using defaultValue if no value is retrieved.

If you want to check for the presence of a property, you can call the Environment’s containsProperty() method, which returns a Boolean type.

In addition to attribute related functionality, Environment provides methods to check which profiles are active.

String[] getActiveProfile(): Returns an array of active profile names

String[] getDefaultProfiles(): Returns the default array of profile names

boolean acceptsProfiles(String … Profile): Environment supports a given profile and returns true.

Parse placeholders

Spring has always supported defining properties to external properties files and inserting them into Spring beans using placeholders. In Spring’s assembly, placeholders are in the form of ${… } The attribute name of the wrapper.

Use the Spring expression language for assembly

Spring3 introduces the Spring Expression Language (SpEL), which provides a powerful and concise way to assemble values into bean properties and constructor parameters, using expressions that are evaluated at run time to get values. With SqEl, you can achieve incredible assembly results that are difficult to achieve with other assembly technologies.

SqEl has many features, including:

The Bean is referenced by its ID

Invoke methods and access properties of objects

Performs arithmetic, relational, and logical operations on values

Regular expression matching

Set operations

SpEL sample

SpEL expressions are placed in “#{… }”, this is similar to attribute placeholders, which are placed in “${… } “.

#{1} After removing the “#{}” tag, what is left is the SpEL expression, which is a numeric constant. The computer result of this expression is the number 1.

#{T(System).currentTimeMillis()}

His end result is the millisecond value of the current time at the moment the expression is evaluated. The T() expression treats java.lang.system as the corresponding type in Java, from which its static modified currentTimeMillis() method can be called.

SpEL expressions can also reference other beans or properties of other beans. For example, the following expression yields the artist attribute for the bean with ID sgtPeppers.

#{sgtPeppers.artise}

We can also reference systemProperties through the systemProperties object.

#{systemProperties[‘disc.title’]}

Representation literals

SpEL can represent integers, floating point numbers, String, and Boolean.

Using literals in SpEL doesn’t really make much sense.

Reference beans, properties, and methods

Another thing that SpEL expressions can do is refer to other beans by ID. You can also move. To refer to properties in the bean.

#{sgtPeppers.artist}

In addition to referring to the bean’s properties, we can also call methods on the bean. For example, if we have another bean whose ID is artistSelector, we can call the bean’s selectArtist() method in an SpEL expression as follows:

#{artistSelector,selectArtist()}

For the return value of the called method, we can also call the method that returns the value. For example, if selectArist returns a String value, we can call toUpperCase() toUpperCase the entire result.

If the return value of selectArtist() is not null, that’s fine. But to avoid errors, we can use type-safe operators:

#{artistSelector.selectArtist()? .toUpperCase()}

The use of “? .” The operator can ensure that its element is not NULL before accessing the content to its right.

Use types in expressions

To access class-scoped methods and constants in SpEL, you rely on the key cloud operator T(). For example, to express the Java Math class in SpEL, use the T() cloud operator as follows:

T(java.lang.Math)

The T() cloud operator here results in a Class object, an instance of the Class, representing java.lang.meth. We can even assemble it into a bean property of type Class if necessary. But the real value of the T() cloud operator is its ability to access static methods and constants of the target type.

The following sample computes a random number between 0 and 1

T(java.lang.Math).random()

SpEL operator.

Operator type The operator
Arithmetic operations +, -, *, /, %, ^
Comparison operations <,>,==,<=,>=,lt,gt,eq,le,ge
Logical operations And, or, not, or
Conditions of operation ? :(ternary),? :(Elvis)
Regular expression matchs

As a simple example of using the above expression, let’s look at the following SpEl expression:

#{2 * T(java.lang.Math).PI * circle.radius}

Not only is this a great example of the multiplication operator (*) in SpEL, it also shows you how to combine simple expressions into more complex ones. Here the value of PI is multiplied by 2, and then multiplied by the value of the RADIUS attribute from the bean with the ID circle. In fact, he calculates the circumference of the circle defined by the Circle bean.

Similarly, you can use the power operator (^) in an expression to calculate the area of a circle

#{T(java.lang.Math).Pi * circle.radius ^ 2}

The “^” is the operator used for power calculations.