Spring 5.0.5 @Value无法解析为正确的类型



我在春季 5 中收到以下错误,并且已经阅读了有关此问题的所有帖子,但没有运气。我刚刚重构了应用程序以通过 PropertiesConfig 类而不是 appliationContext 使用@Configuration.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 {
}

属性配置.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;
}
}

请并感谢您的任何帮助!

找出问题 - 有两个。

首先,你必须在 PropertiesFactoryBean 上调用 .afterPropertiesSet((,否则 .getObject(( 返回 null。

@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;
}

其次,您必须在具有两个属性的 PropertySourcesPlaceholderConfigurer 上调用 "setPropertiesArray((":

PropertySourcesPlaceholderConfigurer commonEnvConfig = new PropertySourcesPlaceholderConfigurer();
commonEnvConfig.setPropertiesArray(commonConfig().getObject(), yamlProperties().getObject());

相关内容

  • 没有找到相关文章

最新更新