본문 바로가기

Web/spring

[Spring Framework Core] 4.3. Language Reference (3)

728x90

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-operator-ternary

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

 

틀린 해석이 있다면 알려주세요 🥸

 

 


 

 

4.3.13. Ternary Operator (If-Then-Else) ~ 4.3.18. Expression templating

 

 

 

 

4.3.13. Ternary Operator (If-Then-Else)

삼항연산자

String falseString = parser.parseExpression(
        "false ? 'trueExp' : 'falseExp'").getValue(String.class);
 
 
parser.parseExpression("name").setValue(societyContext, "IEEE");
societyContext.setVariable("queryName", "Nikola Tesla");

expression = "isMember(#queryName)? #queryName + ' is a member of the ' " +
        "+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";

String queryResultString = parser.parseExpression(expression)
        .getValue(societyContext, String.class);
// queryResultString = "Nikola Tesla is a member of the IEEE Society"

 

 

4.3.14. The Elvis Operator

위의 ternary operator보다 짧다

String name = "Elvis Presley";
String displayName = (name != null ? name : "Unknown");

 

연산자 이용

ExpressionParser parser = new SpelExpressionParser();

String name = parser.parseExpression("name?:'Unknown'").getValue(new Inventor(), String.class);
System.out.println(name);  // 'Unknown'

 

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
String name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String.class);
System.out.println(name);  // Nikola Tesla

tesla.setName(null);
name = parser.parseExpression("name?:'Elvis Presley'").getValue(context, tesla, String.class);
System.out.println(name);  // Elvis Presley

 

 

 

@Value 로 기본 값 적용해주기

@Value("#{systemProperties['pop3.port'] ?: 25}")

pop3.port 값이 없다면 임의의 25를 주입해준다

 

 

 

 

4.3.15. Safe Navigation Operator

 

NullPointerException 을 피하기 위한 Groovy language

개체에 대한 참조가 있을 때 개체의 method나 속성에 null값을 체크해준다

throw 대신 null을 반환하게 하여 안전한 코드를 유지한다

 

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));

String city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String.class);
System.out.println(city);  // Smiljan

tesla.setPlaceOfBirth(null);
city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String.class);
System.out.println(city);  // null - does not throw NullPointerException!!!

 

 

 

4.3.16. Collection Selection

Selection uses a syntax of .?[selectionExpression] 

컬렉션을 필터링 후 원래 요소의 하위 집합을 포함한 새 컬렉션을 반환한다

 

List<Inventor> list = (List<Inventor>) parser.parseExpression(
        "members.?[nationality == 'Serbian']").getValue(societyContext);

Selection is supported for arrays and anything that implements java.lang.Iterable or java.util.Map. 

 

Map newMap = parser.parseExpression("map.?[value<27]").getValue();

 

선택 요소가 아닌, 첫번째 마지막 요소만 검색할 수 있다

.^[selectionExpression] 첫번째 요소 

.$[selectionExpression] 마지막 요소

 

 

 

4.3.17. Collection Projection

 

projection을 사용하면 하위 식에 대한 evaluation을 구동하고 그 결과가 새 컬렉션이 된다

.![projectionExpression] 를 사용하여 하위 항목을 체크하여 리스트화 할 수 있다

 

// returns ['Smiljan', 'Idvor' ]
List placesOfBirth = (List)parser.parseExpression("members.![placeOfBirth.city]");

Projection is supported for arrays and anything that implements java.lang.Iterable or java.util.Map. When using a map to drive projection, the projection expression is evaluated against each entry in the map (represented as a Java Map.Entry). The result of a projection across a map is a list that consists of the evaluation of the projection expression against each map entry.

 

 

 

4.3.18. Expression templating

Expression templates 을 사용하여 평가 블록과 혼합할 수 있다 보통은 #{} 구분기호로 사용하나보다

 

String randomPhrase = parser.parseExpression(
        "random number is #{T(java.lang.Math).random()}",
        new TemplateParserContext()).getValue(String.class);

// evaluates to "random number is 0.7038186818312008"
public class TemplateParserContext implements ParserContext {

    public String getExpressionPrefix() {
        return "#{";
    }

    public String getExpressionSuffix() {
        return "}";
    }

    public boolean isTemplate() {
        return true;
    }
}
728x90