programing

스프링 3 표현 언어는 부동산 플레이스홀더와 어떻게 상호 작용합니까?

oldcodes 2023. 9. 6. 22:17
반응형

스프링 3 표현 언어는 부동산 플레이스홀더와 어떻게 상호 작용합니까?

스프링 3는 콩 정의에 사용할 수 있는 새로운 표현 언어(SpEL)를 도입했습니다.구문 자체는 상당히 잘 명시되어 있습니다.

명확하지 않은 점은 SpEL이 이전 버전에 이미 존재했던 속성 자리 표시자 구문과 어떻게 상호 작용하는지 여부입니다.SpEL이 부동산 플레이스홀더를 지원합니까, 아니면 두 메커니즘의 구문을 결합하고 결합을 희망해야 합니까?

구체적인 예를 들어보겠습니다.속성 구문을 사용합니다.${x.y.z}, 그러나 엘비스 오퍼레이터가 제공하는 "기본값" 구문을 추가하여 다음과 같은 경우를 처리합니다.${x.y.z}정의되지 않았습니다.

저는 다음 구문을 시도했지만 성공하지 못했습니다.

  • #{x.y.z?:'defaultValue'}
  • #{${x.y.z}?:'defaultValue'}

첫번째 것은 나에게 줍니다.

'org.springframework' 유형의 개체에서 'x' 필드 또는 속성을 찾을 수 없습니다.콩.공장.구성Bean ExpressionContext'

SpEL은 이를 재산상의 소유자로 인정하지 않습니다.

두 번째 구문은 자리 표시자를 인식할 수 없으므로 자리 표시자 확인자가 호출되고 있지만 속성이 정의되지 않았기 때문에 예상대로 실패하고 있다는 예외를 발생시킵니다.

문서에는 이 상호작용에 대한 언급이 없으므로 이러한 상호작용이 불가능하거나 문서화되지 않았습니다.

누가 이런 짓을 했습니까?


좋아요, 여기에 대한 작은 자체 테스트 케이스를 생각해냈어요.이 모든 기능은 그대로 작동합니다.

첫째, 콩의 정의:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:util="http://www.springframework.org/schema/util"
           xsi:schemaLocation="
                http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/util    http://www.springframework.org/schema/util/spring-util.xsd
           "> 

    <context:property-placeholder properties-ref="myProps"/>

    <util:properties id="myProps">
        <prop key="x.y.z">Value A</prop>
    </util:properties>

    <bean id="testBean" class="test.Bean">
            <!-- here is where the magic is required -->
        <property name="value" value="${x.y.z}"/> 

            <!-- I want something like this
        <property name="value" value="${a.b.c}?:'Value B'"/> 
            --> 
    </bean>     
</beans>

그러면 사소한 콩 클래스.

패키지 시험;

public class Bean {

    String value;

    public void setValue(String value) {
        this.value = value;
    }
}

그리고 마지막으로 테스트 케이스:

package test;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PlaceholderTest {

    private @Resource Bean testBean;

    @Test
    public void valueCheck() {
        assertThat(testBean.value, is("Value A"));
    }
}

과제 - 다음과 같은 경우에 기본값을 지정할 수 있는 SpEL 표현식을 콩 파일에 제안합니다.${x.y.z}확인할 수 없으며 이 기본값은 다른 속성 집합에서 외부화되지 않고 식의 일부로 지정해야 합니다.

SpEL 식에서 속성 자리 표시자에 액세스하려면 다음 구문을 사용할 수 있습니다.#{'${x.y.z}'}. 그러나, 그것은 엘비스 연산자와 기본값으로 당신의 문제를 해결할 수 없습니다. 왜냐하면 그것은 예외를 던질 것이기 때문입니다.${x.y.z}확인할 수 없습니다.

그러나 SpEL이 속성의 기본값을 선언할 필요는 없습니다.

<context:property-placeholder location="..." properties-ref="defaultValues"/>

<bean id = "defaultValues" class = "org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="properties">
        <props>
            <prop key="x.y.z">ZZZ</prop>
        </props>
    </property>
</bean>

<bean ...>
    <property name = "..." value = "${x.y.z}" />
</bean>

대장을 놓치신 것 같네요

#{ ${x.y.z} ?: 'defaultValue' }

${myProps.item:defaultValue}그 뜻은 다음과myProps.item지음,용을 사용합니다.defaultValue표시자의 입니다. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

#{defaultValue}리터럴 값에 대한 SpEL을 의미합니다.

그렇게,${myProps.item:#{defaultValue}}함 일 때를 합니다.myProps.item존재하지 않습니다. 그런 다음 SpEL 값을 계산하여 대상 필드에 할당합니다.

예:

${redis.auth:#{null}}함 일 때를 합니다.redis.auth다로 하십시오. 다음으로 설정하십시오.null.

자리 표시자에 대한 기본값만 설정하려면 다음을 참조하십시오.

   <property name="value" value="${x.y.z:defaultValue}"/> 

SpEL과 자리 표시자와의 교호작용을 검정하려면 다음을 사용합니다.

   <!-- set value "77-AA-BB-CC-88" when property "x.y.z" not exist -->
   <property name="value" value="77-#{'AA-${x.y.z:BB}-CC'}-88"/>

[ Property-Placeholder ] 문제 컨텍스트에서 있습니다 사용하여 있습니다 해결설정명시적으로 지정 기본 속성실제로 property 있습니다 , 지정 using settings 실제로 property default context spring holder explicit - place specify 있습니다 , 해결문제 i 컨텍스트에서 ly spring - Placeholder 사용하여 can 속성 in you 명시적으로properties다음 의 위치를 하고 속성을 할 수 . 의 를 하고 을 할 할 할 을 하고 를 의 할 localOverridetrue이 리소스에서 수 모든 (. 에서 됨 됨 ( )locationproperty)는 기본값을 재정의합니다(구체적으로 컨텍스트 내에서 정의됨)

내가 도와줬기를.

예제 내에서 실행하려면 이를 추가해야 합니다.

<bean id="testBean" class="elvis.Bean">
        <!-- here is where the magic is required
    <property name="value" value="${x.y.z}"/>
    -->

        <!-- I want something like this -->
    <property name="value" value="#{myProps.get('a.b.c')?:'Value B'}"/>

</bean>

이 Spring을 평가하려고 방식은 효과가 .${a.b.c}목적물에 대하여a멤버과와 b멤버과와 c는는가n이기 때문에 합니다.a존재하지 않습니다.

당신은 다음과 같이 하십시오.

<bean id="testBean" class="test.Bean">
        <!-- if 'a.b.c' not found, then value="Value B" --->
       <property name="value" value="${a.b.c:Value B}"/> 
</bean>     

아니면

 ...
 <!-- if 'a.b.c' not found , but 'a.b' found ,then value=${a.b}
      if 'a.b' also not found , then value="a"     
 -->
 <property name="value" value="${a.b.c:${a.b:a}"/> 
 ...

아니면...

   <!-- if 'a.b.c' not found , but 'a.b' found ,then value=${a.b}
      if 'a.b' also not found , then value="a"     
    -->
       <property name="value" value="#{  '${a.b.c:}'  ?: '${a.b:a}' }"/> 
   ...

나는 다음을 시도해 보았는데 효과가 있었습니다. (그래도 꽤 못생겼습니다.)

#{ myProps.getProperty('x.y.z')?:'Value B' }

엘비스를 쓸 필요는 없어요 대장 뒤에 기본값만 줘요

@Value("${my.connection.timeout:5000}")
private int myTimeoutMillis;

아니면

@Retryable(maxAttemptsExpression = "#{${my.max.attempts:10}}")
public void myRetryableMethod() {
    // ...
}

언급URL : https://stackoverflow.com/questions/2041558/how-does-spring-3-expression-language-interact-with-property-placeholders

반응형