In front of the dependency injection, we are generally a property of injecting a bean reference into another bean or constructor parameter or setter parameter, which is about to associate an object with another object.
Another aspect of bean assembly is the injection of a value into the bean's property or constructor parameter, which we can hard code in the configuration class, which is also hard-coded in the XML (all values are written out).
1, if you want to avoid hard coding, so that these values at run time to determine, spring provides two ways to evaluate at run time.
- The attribute placeholder (property placeholder)--spring supports the definition of an attribute to an external property file, and then inserts it into the spring bean with a placeholder.
- Spring expression Language (spel)
2. Inject values from external (property source)
In spring, the simplest way to handle external values is:
Declaring a property source--@PropertySource ("Classpath:/xxx/xxx/app.property")
The property value--env.getproperty ("XXX") is retrieved through spring's environment.
This allows us to use the values in the external file to complete the injection.
3. Environment API in spring
This interface represents the running environment of the current running program and can retrieve properties directly from environment.
(Detailed analysis reference: http://jinnianshilongnian.iteye.com/blog/2000183)
4. Parsing attribute placeholders
Placeholder form: "${disc.title}" (property name in parentheses)
Parsing an external property enables you to defer processing of a value to the runtime, which resolves properties from spring environment and property sources by name.
5. Assemble with Spel (very powerful)
The Spring expression language provides a more general way to calculate the values to inject at run time, which can result in an unimaginable assembly effect.
Spel expressions are placed in "#{}". (When configured)
Spel can represent literals, such as floating point, String values, and Boolean values:
#{3.14159}, #{' Hello '}, #{false}
Spel can refer to beans (by id), attributes, and methods;
#{beanid}, #{beanid.field}, #{beanid.method ()}
The result of the operator T () is a class object whose value is the ability to access static methods and constants of the target class, for example:
T (Java.lang.Math). Random ()
Spel also provides a number of other operators as well as rich arithmetic functions.
Spring Combat (eight) run-time-value injection of bean assembly-property placeholders and Spel