2017-12-29 11 views
0

이렇게 yml 파일을 읽으려고합니다.@Value는 읽을 수 있지만 @ConfigurationProperties는 없습니다.

order: 
    foo: 5000 
    bar: 12 

그리고 나는 @value으로 읽을 수 있습니다. YML 파일이 더 착물 될 것입니다 때문에 내가 @ConfigurationProperties를 사용하기 위해 노력하고있어

@Component 
@Data 
public class WebConfigProperty { 

    private Integer foo; 
    private Integer bar; 

    public WebConfigProperty(@Value("${order.foo}") @NonNull final Integer foo, 
      @Value("${order.bar}") @NonNull final Integer bar) { 
     super(); 
     this.foo = foo; 
     this.bar = bar; 
    } 
} 

(내가 BTW 롬복을 사용하고 있습니다). 하지만 @ConfigurationProperties에서는 작동하지 않습니다.

@Component 
@ConfigurationProperties("order") 
@Data 
public class WebConfigProperty { 

    @NonNull 
    private Integer foo; 
    @NonNull 
    private Integer bar; 
} 

나는 또한 설정 클래스에 @EnableConfigurationProperties을 추가했다. 설정의 모든 주석은 다음과 같습니다.

@SpringBootConfiguration 
@EnableConfigurationProperties 
@EnableAutoConfiguration(exclude = { ... }) 
@ComponentScan(basePackages = { ... }) 
@Import({ ... }) 
@EnableCaching 

오류 메시지는 다음과 같습니다.

*************************** 
APPLICATION FAILED TO START 
*************************** 

Description: 

Parameter 0 of constructor in {...}.WebConfigProperty required a bean of type 'java.lang.Integer' that could not be found. 


Action: 

Consider defining a bean of type 'java.lang.Integer' in your configuration. 

IT는 YML 파일을 찾아 WebConfigProperty 필드에 null 값을 넣어 시도 할 수없는 봄처럼 보인다. 나는 이유를 모른다.

참고로 FYI는 Gradle을 사용하는 다중 프로젝트 응용 프로그램입니다. yml 파일과 구성 클래스 (작성되지 않음)는 동일한 프로젝트에 있습니다. WebConfigProperty은 다른 프로젝트에 있습니다.

편집 : @Yannic Klem의 답변에 따르면이 두 가지가 작동했습니다.

@Component 
@ConfigurationProperties("order") 
@Getter 
@Setter 
@EqualsAndHashCode 
public class WebConfigProperty { 

    @NonNull 
    private Integer foo; 
    @NonNull 
    private Integer bar; 
} 

//OR 

@Component 
@ConfigurationProperties("order") 
@Data 
@NoArgsConstructor 
public class WebConfigProperty { 

    @NonNull 
    private Integer foo; 
    @NonNull 
    private Integer bar; 
} 
+0

나는 문제가'Data' @ 주석라고 생각합니다. 나는 답을 주었지만 지금은 확인할 수 없다. '@Data' 주석이 아닌지 말해주세요 –

+2

'@ Data' 대신'@ Getter'와'@Setter'를 명시 적으로 사용하십시오. – pvpkiran

+0

'@ConfigurationProperties (prefix = "order")'로 시도해도 될까요? –

답변

2

Lomboks @Data 주석은 @RequiredArgsConstructor 추가합니다. 그러면 Spring은 생성자에 인수를 자동 전달하려고 시도합니다.

Integer : foo 및 bar 유형의 두 bean을 조회하려고하기 때문에 예외가 발생합니다.

@ConfigurationProperties에는 속성에 대한 기본 생성자와 getters + setter 만 있어야합니다. 그런 다음 속성은 해당 설정자가 @ConfigurationProperties 클래스에 바인딩합니다.

귀하의 WebConfigProperty는 다음과 같이 수 :

@Component 
@ConfigurationProperties("order") 
/** 
* Not sure about IDE support for autocompletion in application.properties but your 
* code should work. Maybe just type those getters and setters yourself ;) 
*/ 
@Getters 
@Setters 
public class WebConfigProperty { 

    @NonNull 
    private Integer foo; 
    @NonNull 
    private Integer bar; 
} 
+0

그것은 효과가 있었다. 고맙습니다. – user2652379

관련 문제