Spring spring using the expression (the EL Spring)

  Spring also provides a more flexible way of injecting that Spring expression, in fact, far more powerful Spring EL injection method, we need to learn it. Spring EL has a lot of features.
  Use id Bean to refer Bean.
  • Call the specified object properties and methods to access the object.
  • carry out operations.
  • Provide regular expression matching.
  • collection configuration.
  These are expressions of Spring content, using Spring expressions can be obtained than using Properties files more powerful assembly capabilities, but sometimes for the convenience of the test can be used to resolve class Spring EL-defined test, for which we come to know them first .

Spring EL related classes

  Spring EL brief introduction of related classes, so that we can test and understanding. First ExpressionParser interface, which is to parse an expression of the interface, since it is an interface, it does not have any specific function, Spring will obviously provide more implementation class

  

 

  Listing: Spring EL illustrates the use of

// expression parser 
ExpressionParser is Parser = new new SpelExpressionParser ();
 // Set the expression 
the Expression parser.parseExpression = exp ( " 'Hello World'" ); 
String STR = (String) exp.getValue (); 
the System.out. the println (STR); 
// the EL common access method 
exp = parser.parseExpression ( " 'world'.charAt Hello (0)" );
 char CH = (Character) exp.getValue (); 
System.out.println (CH ); 
// by getter methods EL access 
exp = parser.parseExpression ( " 'world'.bytes Hello" );
 byte [] bytes = ( byte []) exp.getValue (); 
System.out.println (bytes) ;
// by EL access attribute corresponds to "Hello World" .getBytes () length. 
Exp = parser.parseExpression ( " 'world'.bytes.length Hello" );
 int length = (Integer) exp.getValue (); 
the System .out.println (length); 
exp = parser.parseExpression ( "new new String ( 'ABC')" ); 
String ABC = (String) exp.getValue (); 
System.out.println (ABC); 

 

// expression parser 
ExpressionParser parser = new new SpelExpressionParser ();
 // create a character object 
Role2 role = new new Role2 (1L, "role_name", "note" ); 
Expression exp = parser.parseExpression ( "note");
//Corresponds to information obtained from the role Memo 
String Note = (String) exp.getValue (role); 
System.out.println (Note); 
// variable environment class, and the role of the character object as its root 
EvaluationContext CTX = new new , StandardEvaluationContext, (Role);
 // variable operating environment class root 
parser.parseExpression ( "note") setValue (ctx, "new_note." );
 // get remarks, String.class specified here, and we hope to return a string 
= parser.parseExpression note ( "note") getValue (ctx, String.. class ); 
System.out.println (note); 
// call getRoleName method 
String roleName = parser.parseExpression ( "getRoleName ( )") getValue (. ctx, String. class ); 
System.out.println (roleName); 
//New Environment Variables 
List <String> List = new new ArrayList <String> (); 
list.add ( "value1" ); 
list.add ( "value2" );
 // to increase variable environment variable 
ctx.setVariable ( "list" , List);
 // through the expression to read / write values of environment variables 
parser.parseExpression ( "# List [1]") setValue (ctx, "update_value2." ); 
System.out.println (parser.parseExpression ( " #list [1] ") getValue ( ctx)).;

 

  EvaluationContext used, StandardEvaluationContext, its implementation class, is instantiated, it is passed to the constructor in the character object, then the content will be valued based on the class resolution. So behind the expression setValue and getValue methods regarded the valuation of content delivery in, so it can read / write the contents of the root node, and by getRole () example, you can know that it can support even calling methods. For greater flexibility, also supports the new valuation of the content and operation of other variables, as the code creates a List, and the List by the valuation method setVariable content settings, its key to "list", thus allowing us #list by reference to the expression inside it, given by the subscript 1, it is representative of a second reference element List (list is the first element identified by a subscript 0).
  Spring has introduced the above analytic function expressions, Spring EL most important function is to inject Bean attributes, let us annotation-based way to learn them.

Bean properties and methods

  Use annotations way you need to use annotations @Value, used in reading the properties file is "$", and then use the "#" in the Spring EL. The following discussion to the role of class as an example, we can initialize its properties, as shown in Listing.
  Listing: use Spring EL initialization character class

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("role2")
public class Role2 {

//赋值long型
@Value("#{2}")
private Long id;
//字符串赋值
@Value("#{'role_name_2'}")
private String roleName;
//字符串赋值
@Value("#{'note_2'}")
private String note;
}

 

  Listing: Properties role referenced by Spring EL, call its methods

@Component ( "elBean" )
 public  class ElBean { 

// Get through beanName bean, and then injected 
@Value ( "role2 # {}" )
 Private Role2 role2; 

// Get bean property ID 
@Value ( "# {role2.id } " )
 Private Long the above mentioned id; 

// call the bean getNote method to get the role name
 // @Value (" # {role.getNote () toString ()} "). 
@Value (" # {role2.getNote ()? .toString ()} " )
 Private String Note; 

@Value ( " # {T (the Math) .PI} " )
 Private  Double PI; 

@Value ( " # {T (the Math) .random ()} ")
private double random;

@Value("#{role.id+1}")
private int num;
}

 

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig3.class);
Role2 role2 = context.getBean(Role2.class);
System.out.println(role2.toString());
ElBean elBean = context.getBean(ElBean.class);
System.out.println(elBean.toString());

 

Static class constants and methods of use  

  Sometimes we might want to use static methods and constants, such as pi π, while in Java is a constant PI Math class, need to inject it very simple, as in the following ElBean in the same operation on it:
  @Value ( "# T {(Math) .PI} ")
  Private Double PI;
  herein represents the Math class under java.lang * Math package. When using the package in the Java code is not required to use the import keyword introduced, for Spring EL as well. If the content of the package in a non-Spring, then be given fully qualified name of the class, need be written like this:
  @Value ( "# {T (java.lang.Math) .PI}")
  Private Double PI ;
  likewise, sometimes using static Math class methods to produce a random number (between 0 and 1 random double precision numbers), this time need to use it to the random method, such as:
  @Value ( "# {T (Math ) .random ()} ")
  Private Double Random;
  so you can load data corresponding to a static method call class.

Spring EL operation

  The above discussed how to get the value, in addition to Spring EL can also be operational, such as adding a number num on ElBean, its value defaults to the requirements of the role number (id) +1, then we can write:

  @Value ( "# role.id +. 1 {}")
  Private int NUM;
  sometimes "+" operator can also be used in the connection string, such as below this field, the properties and roleName note character objects connected:
  @Value ( "# {} role.note role.roleName +")
  Private string STR;
  This makes it possible to obtain a character string names and comments are connected. Compare two values are equal, such as role id is 1, if the role name is "role_name_001". Numbers and strings can be used "EQ" or "==" equality comparison. In addition, there is greater than, less than or equal mathematical operations, such as:
  @Value ( "# role.id == {}. 1")
  Private Boolean equalNum;
  @Value ( "# {role.note EQ 'note_1'}" )
  Private Boolean eqaulString;
  @Value ( "# {role.id> 2}")
  Private Boolean Greater;
  @Value ( "# {role.id <2}")
  Private Boolean less;
  in Java, you might miss three head operation, for example, if the character number is greater than 1, then the value 5, or the value 1, it can be written in Java:
  int max = (role.getId ()>
  If the role of notes is empty, we give it a default initial value "note", it is written using Java:  
  String defaultString = (role.getNote () == null "the Hello":? Role.getNote ());
  Let we go to achieve the above functions by String EL.
  @Value ( "# {? Role.id>. 1. 5:}. 1")
  Private int max;
  @value ( "# {role.note ?: 'Hello'}")
  Private String defaultString;
  in fact do much Spring EL more than that, the above only describes some of the most basic, the most commonly used functions, skilled use of it requires readers to more hands-on practice.

 

 

Source: ssm10.10

Guess you like

Origin www.cnblogs.com/ooo0/p/10987630.html