Spring (23) -- SPEL 표현 식 (4)
23.2.24 기본 값 설정
SpEl 표현 식 에 서 는 "a?: b" 라 는 문법 을 지원 하여 기본 값 을 설정 합 니 다.a 가 null 이 아 닐 때 그 결 과 는 a 이 고 그렇지 않 으 면 b 라 는 뜻 이다.
@Test
public void test24 () {
ExpressionParser parser = new SpelExpressionParser();
Assert.assertTrue(parser.parseExpression("#abc?:123").getValue().equals(123));// abc
Assert.assertTrue(parser.parseExpression("1?:123").getValue().equals(1));// 1 null
}
23.2.25 안전 항 법
"a. b. c" 와 같은 용법 을 자주 사용 할 수 있 습 니 다. a 의 b 속성 을 나타 내 는 c 속성 이지 만 a 가 null 이거 나 a 의 b 속성 이 null 이면 빈 포인터 가 나타 납 니 다.이러한 상황 을 피하 기 위해 서, 우 리 는 SpEl 표현 식 에서 안전 한 내 비게 이 션 을 사용 할 수 있 습 니 다. 이렇게 하면 a 가 null 또는 a 의 b 속성 이 null 일 때 빈 포인터 이상 을 던 지지 않 고 null 로 돌아 갑 니 다.SpEl 표현 식 에서 보안 내 비게 이 션 의 문법 은 점 "." 을 "?." 로 바 꾸 는 것 입 니 다. 즉, "a. b. c" 를 사용 하지 않 고 "a? b? c" 를 사용 합 니 다.
@Test
public void test25 () {
ExpressionParser parser = new SpelExpressionParser();
Assert.assertNull(parser.parseExpression("null?.abc").getValue());
Assert.assertNull(parser.parseExpression("T(System)?.getProperty('abc')?.length()").getValue());// 1 null
}
23.2.26 bean 대상 가 져 오기
SpEL 표현 식 에서 도 bean 대상 을 직접 방문 할 수 있 습 니 다. 전 제 는 Bean Resolver 를 지정 한 것 입 니 다.BeanResolver 는 하나의 인터페이스 로 하나의 방법 으로 만 resolve 를 정의 합 니 다. beanName 을 통 해 대응 하 는 bean 대상 으로 분석 하고 되 돌려 줍 니 다. 구체 적 인 정 의 는 다음 과 같 습 니 다.
public interface BeanResolver {
Object resolve(EvaluationContext context, String beanName) throws AccessException;
}
SpEL 표현 식 에서 bean 대상 을 방문 하려 면 Standard Evaluation Context 를 통 해 해당 하 는 Bean Resolver 를 설정 해 야 합 니 다. 또한 SpEL 표현 식 에서 "@ beanName" 방식 으로 대응 하 는 bean 대상 을 방문 해 야 합 니 다.다음은 예제 코드 입 니 다. 표현 식 에서 hello 라 는 bean 대상 을 얻 었 고 getKey () 방법 에 접근 하 였 습 니 다.
@Test
public void test26() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new MyBeanResolver());
// bean hello bean getKey() 。
Object obj = parser.parseExpression("@hello.key").getValue(context);
System.out.println(obj);
}
private static class MyBeanResolver implements BeanResolver {
private static ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
public Object resolve(EvaluationContext context, String beanName)
throws AccessException {
return appContext.getBean(beanName);
}
}
23.3 SpelParserConfiguration
SpelExpressionParser 를 구축 할 때 우 리 는 SpelParser Configuration 대상 을 전달 하여 SpelExpressionParser 를 설정 할 수 있 습 니 다.List 나 Array 가 null 일 때 자동 으로 new 에 대응 하 는 인 스 턴 스 를 지정 할 수 있 습 니 다. SpelParser Configuration 에 대응 하 는 첫 번 째 구조 적 매개 변 수 를 지정 할 수 있 습 니 다.List 나 Array 에서 대응 하 는 색인 이 현재 색인 의 최대 치 를 초과 할 때 자동 으로 확장 할 지 여 부 를 지정 할 수 있 습 니 다. SpelParser Configuration 에 대응 하 는 두 번 째 구조 적 매개 변 수 는 Spring 의 API 문 서 를 참고 하 십시오.다음 예제 에서 저 희 는 SpelParser Configuration 대상 을 사 용 했 습 니 다. 해당 하 는 List 나 Array 가 null 일 때 자동 으로 new 에 대응 하 는 대상 을 지정 하고 해당 하 는 색인 이 List 나 Array 의 현재 최대 색인 을 초과 할 때 자동 으로 확장 합 니 다.따라서 다음 예제 에 서 는 사용자 의 interests 를 처음 방문 할 때 null 이 고, 그 다음 두 번 째 방문 할 때 자동 new 에 대응 하 는 대상 을 지정 하고 색인 이 초과 되 었 을 때 자동 으로 확장 하기 때문에 new List 의 인 스 턴 스 를 Array List 에 대응 하 며, 색인 5 가 존재 하지 않 을 때 자동 으로 확장 하고 입력 합 니 다.값 을 입력 할 때 List 의 요소 형식 String new 를 6 회 입력 합 니 다.따라서 이러한 상황 에 대해 우 리 는 List 나 Array 에 저 장 된 요소 유형 에 무 참 구조 방법 이 존재 하 는 것 을 보증 해 야 한다.
class User {
public List<String> interests;
}
@Test
public void test() {
User user = new User();
SpelParserConfiguration parserConfig = new SpelParserConfiguration(true, true);
ExpressionParser parser = new SpelExpressionParser(parserConfig);
// null
Assert.assertNull(parser.parseExpression("interests").getValue(user));
// new List , ArrayList, new String() 6 。
Assert.assertTrue(parser.parseExpression("interests[5]").getValue(user).equals(""));
//size 6
Assert.assertTrue(parser.parseExpression("interests.size()").getValue(user).equals(6));
}
23.4 bean 정의 에서 SpEl 사용
bean 정의 에서 SpEl 표현 식 을 사용 하 는 문법 은 '\ # {exp}' 입 니 다.exp 는 대응 하 는 표현 식 입 니 다.다음 예제 에서 우 리 는 hello 라 는 bean 을 정 의 했 습 니 다. userDir 를 지정 할 때 표현 식 을 사 용 했 습 니 다.
<bean id="hello" class="com.app.Hello">
<property name="userDir" value="#{T(System).getProperty('user.dir')}"/>
bean>
시스템 속성 에 있어 서 bean 정의 에서 사용 할 때 내 장 된 변 수 는 systemProperties 라 고 할 수 있 으 며 사용 할 때 '\ #' 를 추가 할 필요 가 없습니다. 즉, '\ # systemProperties' 형식 으로 나타 날 필요 가 없습니다.그래서 상술 한 예시 도 다음 과 같다.
<bean id="hello" class="com.elim.learn.spring.bean.Hello">
<property name="userDir" value="#{systemProperties['user.dir']}"/>
bean>
23.4.1 다른 bean 의 속성 참조
bean 정 의 를 진행 할 때, 우 리 는 표현 식 을 통 해 다른 bean 정의 속성 을 참조 할 수 있 습 니 다.다음 예제 에서 우 리 는 id 가 World 인 bean 의 key 속성 을 정의 할 때 표현 식 을 통 해 hello 라 는 bean 의 key 속성 을 참조 하 였 습 니 다. 즉, World 의 key 속성 도 값 'abc' 를 부여 합 니 다.
<bean id="hello" class="com.app.Hello">
<property name="key" value="abc"/>
bean>
<bean id="world" class="com.app.World">
<property name="key" value="#{hello.key}"/>
bean>
23.4.2 주석 기반 설정 사용
주해 설정 을 기반 으로 한 bean 정의 에서 도 SpEl 표현 식 을 사용 하여 정 의 를 내 릴 수 있 습 니 다.주 해 를 기반 으로 bean 정 의 를 설정 할 때 @ Value 주 해 를 사용 하여 방법 이나 속성 에 대응 하 는 값 을 지정 할 수 있 습 니 다.이때 우 리 는 대응 하 는 표현 식 을 사용 할 수 있 습 니 다. 물론 표현 식 을 사용 하지 않 아 도 됩 니 다.다음 예제 에서 저 희 는 @ Value 를 통 해 userDir 와 key 의 값 을 지정 합 니 다.그 중에서 userDir 의 값 정 의 는 SpEl 표현 식 을 사 용 했 고 key 의 값 정 의 는 직접적 으로 정의 되 었 습 니 다.
public class Hello {
@Value("#{systemProperties['user.dir']}")
private String userDir;
@Value("abc")
private String key;
public String getUserDir() {
return userDir;
}
public void setUserDir(String userDir) {
this.userDir = userDir;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
(주: 본 고 는 Spring 4.1.0 을 바탕 으로 쓴 것 이다)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.