복붙노트

[SPRING] @Component와 @Autowired를 사용할 때 스프링 빈 원시 속성?

SPRING

@Component와 @Autowired를 사용할 때 스프링 빈 원시 속성?

Bean의 프리미티브 속성 값을 설정하는 방법?

@Component 어노테이션이 있고 @Autowired 어노테이션도 인스턴스 종속성을 바인딩하기위한 것이므로 원시 속성은 어떨까요?

@Component
class Person{
@Autowired
Address address;

int age /// what about this one?
}

해결법

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

    1.프리미티브의 경우 @Value 주석을 사용할 수 있습니다. 일반적인 시나리오는 속성 파일에서 값을로드 한 PropertyPlaceholderConfigurer를 가지고 @Value ( "$ {property.key}")를 사용하는 것입니다.

    프리미티브의 경우 @Value 주석을 사용할 수 있습니다. 일반적인 시나리오는 속성 파일에서 값을로드 한 PropertyPlaceholderConfigurer를 가지고 @Value ( "$ {property.key}")를 사용하는 것입니다.

    값을 빈 (bean)으로 정의 할 수도 있습니다. 이는 더 오래된 학교입니다.

    <bean id="foo" class="java.lang.Integer" factory-method="valueOf">
        <constructor-arg value="20" />
    </bean>
    

    그리고

    @Autowired
    @Qualifier("foo")
    private int foo;
    
  2. ==============================

    2.나는 Bozho가 제안한 두 번째 접근법을 시도했다. 그것은 작동하지 않는 것 같습니다.

    나는 Bozho가 제안한 두 번째 접근법을 시도했다. 그것은 작동하지 않는 것 같습니다.

    아래는 작동 중입니다. bean을 다음과 같이 정의하십시오.

    <bean id="foo" class="java.lang.Integer" factory-method="valueOf">
         <constructor-arg value="20" />
    </bean>
    

    그리고

    @Autowired
    @Qualifier("foo")
    private java.lang.Integer foo;
    

    또는

    @Autowired
    private java.lang.Integer foo;
    
  3. from https://stackoverflow.com/questions/5467803/spring-bean-primitive-properties-when-using-component-and-autowired by cc-by-sa and MIT license