Spring 5.0.5 @Value не может исправить тип - PullRequest
0 голосов
/ 01 мая 2018

Весной 5 я получаю следующую ошибку, и безуспешно прочитал все посты по этой проблеме. Я просто реорганизовал приложение для использования @Configuration через класс PropertiesConfig вместо appliationContext.xml для определения заполнителя свойства

Unsatisfied dependency expressed through field 'secureExpirationHours'; nested 
exception is org.springframework.beans.TypeMismatchException: Failed to convert 
value of type 'java.lang.String' to required type 'int'; nested exception is 
java.lang.NumberFormatException: For input string: "${asset.href.expiration.hours.secure}

Ссылка на переменную:

public class TestRepository {
    @Value("${asset.href.expiration.hours.secure}")
    private int secureExpirationHours;
}

Смешанная конфигурация:

@Configuration
@ComponentScan
@Import({PropertiesConfig.class})
@ImportResource({
    "classpath:META-INF/spring/applicationContext-assets.xml",
    "classpath:META-INF/spring/applicationContext-mongo.xml",
    "classpath:META-INF/spring/applicationContext-security.xml",
    "classpath:META-INF/spring/applicationContext.xml"})
public class CoreConfig {
}

PropertiesConfig.class:

@Configuration
public class PropertiesConfig {

    public static PropertySourcesPlaceholderConfigurer commonEnvConfig;

    @Bean(name="commonConfig")
    public static PropertiesFactoryBean commonConfig() {
        PropertiesFactoryBean commonConfig = new PropertiesFactoryBean();
        commonConfig.setLocation(new ClassPathResource("META-INF/spring/config.properties"));
        return commonConfig;
    }

    @Bean(name="envProperties")
    public static YamlPropertiesFactoryBean yamlProperties() {
          YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
          yaml.setResources(new ClassPathResource("application-dev.yaml"));
          return yaml;
    }

    @Bean(name="commonConfigPropertyPlaceholder")
    public static PropertySourcesPlaceholderConfigurer commonConfigPropertyPlaceholder() throws IOException {
        if (commonEnvConfig == null) {
            commonEnvConfig = new PropertySourcesPlaceholderConfigurer();
        }

        PropertiesFactoryBean commonConfig = PropertiesConfig.commonConfig();
        try {
            commonEnvConfig.setProperties(commonConfig.getObject());
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

        YamlPropertiesFactoryBean yaml = PropertiesConfig.yamlProperties();
        commonEnvConfig.setProperties(yaml.getObject());
        commonEnvConfig.setIgnoreUnresolvablePlaceholders(true);

        return commonEnvConfig;
    }
}

Пожалуйста и спасибо за любую помощь!

1 Ответ

0 голосов
/ 02 мая 2018

Разобрался с проблемой (ами) - их две.

Прежде всего, вы должны вызвать .afterPropertiesSet (); в PropertiesFactoryBean, в противном случае .getObject () возвращает ноль.

@Bean(name="commonConfig")
public static PropertiesFactoryBean commonConfig() throws IOException {
    PropertiesFactoryBean commonConfig = new PropertiesFactoryBean();
    commonConfig.setLocation(new ClassPathResource("META-INF/spring/config.properties"));
    try {
        commonConfig.afterPropertiesSet();
    }
    catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
    return commonConfig;
}

Во-вторых, вы должны вызвать "setPropertiesArray ()" для PropertySourcesPlaceholderConfigurer с обоими свойствами:

    PropertySourcesPlaceholderConfigurer commonEnvConfig = new PropertySourcesPlaceholderConfigurer();
    commonEnvConfig.setPropertiesArray(commonConfig().getObject(), yamlProperties().getObject());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...