복붙노트

[SPRING] Spring @Value 주석에서 기본값을 올바르게 지정하는 방법은 무엇입니까?

SPRING

Spring @Value 주석에서 기본값을 올바르게 지정하는 방법은 무엇입니까?

처음에는 다음 사양이 있습니다.

@Value("#{props.isFPL}")
private boolean isFPL=false;

속성 파일에서 값을 가져 오는 것이 올바르게 작동합니다.

isFPL = true

그러나 다음과 같은 기본 표현식은 오류를 발생시킵니다.

@Value("#{props.isFPL:false}")
private boolean isFPL=false;

식 구문 분석에 실패했습니다. 중첩 예외는 org.springframework.expression.spel.SpelParseException입니다. EL1041E : (pos 28) : 유효한 표현식을 구문 분석 한 후에도 표현식에 더 많은 데이터가 있습니다 : 'colon (:)'

또한 # 대신 $를 사용하려고했습니다.

@Value("${props.isFPL:true}")
private boolean isFPL=false;

그런 다음 주석의 기본값은 정상적으로 작동하지만 속성 파일에서 올바른 값을 얻지 못했습니다.

해결법

  1. ==============================

    1.다음과 같이 $로 시도하십시오

    다음과 같이 $로 시도하십시오

    @Value("${props.isFPL:true}")
    private boolean isFPL=false;
    

    또한 특성 파일이 누락 된 경우 기본값이 사용되도록 ignore-resource-not-found를 true로 설정하십시오.

    또한 다음에-

    xm 기반 구성을 사용하는 경우 컨텍스트 파일 :

    <context:property-placeholder ignore-resource-not-found="true"/>
    

    Java 구성을 사용하는 경우 구성 클래스에서 :

     @Bean
     public static PropertySourcesPlaceholderConfigurer   propertySourcesPlaceholderConfigurer() {
         PropertySourcesPlaceholderConfigurer p =  new PropertySourcesPlaceholderConfigurer();
         p.setIgnoreResourceNotFound(true);
    
        return p;
     }
    
  2. ==============================

    2.int 유형 변수의 경우 :

    int 유형 변수의 경우 :

    @Value("${my.int.config: #{100}}")
    int myIntConfig;
    

    참고 : 콜론 앞에는 공백이 없지만 콜론 뒤에는 공백이 있습니다.

  3. ==============================

    3.Spring 애플리케이션 컨텍스트 파일에 아래와 같이 하나 이상의 propertyPlaceholder Bean이 포함되어 있습니까?

    Spring 애플리케이션 컨텍스트 파일에 아래와 같이 하나 이상의 propertyPlaceholder Bean이 포함되어 있습니까?

    <context:property-placeholder ignore-resource-not-found="true" ignore-unresolvable="true" location="classpath*:/*.local.properties" />
    <context:property-placeholder location="classpath:/config.properties" />
    

    그렇다면 props.isFPL은 첫 번째 특성 파일 (.local.properties)에 대해서만 특성 검색을 수행하며, 특성을 찾을 수없는 경우 기본값 (true)이 적용되고 두 번째 특성 파일 (config.properties)이 적용됩니다. )는이 속성에서 효과적으로 무시됩니다.

  4. ==============================

    4.다음과 같은 것을 사용하는 경우 속성을로드하는 방법에 따라

    다음과 같은 것을 사용하는 경우 속성을로드하는 방법에 따라

    그런 다음 @Value는 다음과 같아야합니다.

    @Value("${isFPL:true}")
    
  5. ==============================

    5.문자열의 경우 다음과 같이 기본값을 null로 설정할 수 있습니다.

    문자열의 경우 다음과 같이 기본값을 null로 설정할 수 있습니다.

    public UrlTester(@Value("${testUrl:}") String url) {
        this.url = url;
    }
    
  6. from https://stackoverflow.com/questions/26916598/how-to-correctly-specify-a-default-value-in-the-spring-value-annotation by cc-by-sa and MIT license