Подтвердить что ты не робот

@Value → Не удалось преобразовать значение типа "java.lang.String" в требуемый тип "java.lang.Integer"

Добрый день, я работаю над веб-приложением, используя Spring 4.1.1.RELEASE. Вся конфигурация Spring выполняется с аннотациями, и она отлично работает, за исключением одного:

  • У меня есть файл config.properties в проекте с этими строками

    cases.caseList.filter=test
    cases.caseList.numberOfCasesPerPage=50
    
  • У меня есть класс конфигурации

    @Configuration
    @ComponentScan(basePackageClasses={CaseConfig.class})
    @PropertySource(value = "classpath:config.properties")
    public class CasesModuleTestContextConfig { ... }
    
  • И еще один класс

    @Component
    public class HttpRequestParamsToPaginationParams extends AbstractConverter<Map<String, String>, PaginationParams> {
    
        @Value("${cases.caseList.filter}")
        private String filter;
    
        @Value("${cases.caseList.numberOfCasesPerPage}")
        private Integer count;
    
        ...
    }
    

Значение свойства "фильтр" успешно вводится из ресурса свойства. Но я получаю исключение по счету "count":

     13:58:45.274 [main] WARN  o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt 
     org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cz.pokus.core.test.config.ConversionServiceTestConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List cz.pokus.core.test.config.ConversionServiceTestConfig.converterList; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'httpRequestParamsToPaginationParams': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Integer cz.pokus.core.cases.converter.HttpRequestParamsToPaginationParams.count; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "${cases.caseList.numberOfCasesPerPage}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.1.RELEASE.jar:4.1.1.RELEASE]
     ...
     Caused by: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "${cases.caseList.numberOfCasesPerPage}"
     ...
     Caused by: java.lang.NumberFormatException: For input string: "${cases.caseList.numberOfCasesPerPage}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_20]
at java.lang.Integer.parseInt(Integer.java:569) ~[na:1.8.0_20]
at java.lang.Integer.valueOf(Integer.java:766) ~[na:1.8.0_20]
     ...

Когда я изменяю тип свойства count на String, он начинает работать:

        @Value("${cases.caseList.numberOfCasesPerPage}")
        private String count;

Я считаю, что Spring может преобразовать String в Integer при вводе значения из ресурса свойства в свойство Integer с использованием @Value. Я нашел примеры, где люди используют, не жалуясь. У вас есть идеи, почему это не работает для меня?

Заранее большое спасибо.

4b9b3361

Ответ 1

Если вы пытаетесь получить доступ к значениям свойств с помощью @Value(""), вы должны объявить PropertySourcesPlaceholderConfigurer Bean.

Попробуйте добавить ниже фрагмент кода в вашем классе конфигурации.

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

Если вы не хотите, чтобы объявить его, попробуйте с org.springframework.core.env.Environment класса, его автоматического связывания в своем классе, чтобы получить значения свойств.

@Autowired
private Environment environment;

public void readValues() {
    System.out.println("Some Message:"
            + environment.getProperty("<Property Name>")); 

}