code

Spring에서 @Value의 기본값으로 null을 설정할 수 있습니까?

codestyles 2020. 10. 4. 11:18
반응형

Spring에서 @Value의 기본값으로 null을 설정할 수 있습니까?


현재 다음과 같이 @Value Spring 3.1.x 주석을 사용하고 있습니다.

@Value("${stuff.value:}")
private String value;

속성이없는 경우 빈 문자열을 변수에 넣습니다. 빈 문자열 대신 기본값으로 null을 사용하고 싶습니다. 물론 stuff.value 속성이 설정되지 않은 경우 오류를 피하고 싶습니다.


PropertyPlaceholderConfigurer 의 nullValue를 설정해야합니다 . 예를 들어 문자열을 사용하고 @null있지만 빈 문자열을 nullValue로 사용할 수도 있습니다.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <!-- config the location(s) of the properties file(s) here -->
    <property name="nullValue" value="@null" />
</bean>

이제 문자열 @null사용 하여 null을 나타낼 수 있습니다.

@Value("${stuff.value:@null}")
private String value;

참고 : 컨텍스트 네임 스페이스는 현재 null 값을 지원하지 않습니다. 당신은 사용할 수 없습니다

<context:property-placeholder null-value="@null" ... />

Spring 3.1.1로 테스트 됨


이것은 정말 오래되었지만 이제 Spring EL을 사용할 수 있습니다.

@Value("${stuff.value:#{null}}")

이 질문을 참조하십시오 .


@vorburger 덕분에 :

@Value("${email.protocol:#{null}}")
String protocol;

다른 구성없이 문자열 값을 null로 설정합니다.


나는 "null-value"에 대해 몰랐기 때문에 @nosebrain 신용을 부여하지만 null, 속성 파일에서 표현하기가 어렵 기 때문에 특히 null 값을 사용하지 않는 것을 선호 합니다.

그러나 여기에 null을 사용하는 대안이 null-value있으므로 속성 자리 표시 자와 함께 작동합니다.

public class MyObject {

   private String value;

   @Value("${stuff.value:@null}")
   public void setValue(String value) {
      if ("@null".equals(value)) this.value = null;
      else this.value = value;
   }
}

개인적으로 저는 나중에 stuff.value쉼표로 구분 된 값 이되기를 원 하거나 Enum 스위치가 더 쉽기 때문에 내 방식을 선호합니다 . 단위 테스트도 더 쉽습니다. :)

편집 : 열거 형 사용에 대한 귀하의 의견과 null을 사용하지 않는다는 의견을 기반으로합니다.

@Component
public class MyObject {

    @Value("${crap:NOTSET}")
    private Crap crap;

    public enum Crap {
        NOTSET,
        BLAH;
    }
}

The above works fine for me. You avoid null. If your property files want to explicit set that they don't want to handle it then you do (but you don't even have to specify this as it will default to NOTSET).

crap=NOTSET

null is very bad and is different than NOTSET. It means spring or unit test did not set it which is why there is IMHO a difference. I still would probably use the setter notation (previous example) as its easier to unit test (private variables are hard to set in a unit test).

참고URL : https://stackoverflow.com/questions/11991194/can-i-set-null-as-the-default-value-for-a-value-in-spring

반응형