使用spring从属性文件中设置int值

时间:2018-07-26 13:34:18

标签: spring properties

尝试使用spring绑定属性文件中的int值

但是每次遇到以下异常时:

Failed to instantiate [org.springframework.amqp.rabbit.connection.ConnectionFactory]: 
Factory method 'connectionFactory' threw exception; nested exception is java.lang.NumberFormatException: For input string: \"${rabitmq.server.host.connectionclosetimeout}\"
Caused by: java.lang.NumberFormatException: For input string: \"${rabitmq.server.host.connectionclosetimeout}\""}}

我的属性文件如下所示:

rabitmq.server.host.connectionclosetimeout=30000

我的豆子

@Value("${rabitmq.server.host.connectionclosetimeout}")
private int connectionCloseTimeOut; 

配置类

@Configuration
@PropertySource("classpath:config/service.properties")
public class RabbitMqConfiguration {

    @Value("${rabitmq.server.host.connectionclosetimeout}")
    private Integer connectionCloseTimeOut;

    /**
     * Establishing connection
     * 
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setCloseTimeout(connectionCloseTimeOut);
        return connectionFactory;
    }       

}

如果我在bean下面添加,那么它的工作正常。但我想不使用以下

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

我也尝试了以下方法:

@Value("#{new Integer.parseInt('${rabitmq.server.host.connectionclosetimeout}')}")
private int connectionCloseTimeOut; 

它也不起作用。

请提出使它工作的方法。

2 个答案:

答案 0 :(得分:0)

您的SPEL不正确。这应该有效

@Value("#{ T(java.lang.Integer).parseInt('${rabitmq.server.host.connectionclosetimeout}') }")
private int connectionCloseTimeOut; 

尝试一下

答案 1 :(得分:0)

以下摘自PropertySource https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

的文档
  

要使用PropertySource的属性解析$ {...}占位符,请使用注册一个PropertySourcesPlaceholderConfigurer。在XML中使用时会自动发生,但是在使用@Configuration类时必须使用静态@Bean方法显式注册。

因此,如果您使用@PropertySource,要解析@Value批注中的$ {...}占位符,则必须通过

注册PropertySourcesPlaceholderConfigurer
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

或通过如下配置XML中的PSPC

<context:property-placeholder location="classpath:config/service.properties" />

请参考春季JIRA票据https://jira.spring.io/browse/SPR-8539和SO线程@Value not resolved when using @PropertySource annotation. How to configure PropertySourcesPlaceholderConfigurer?,以获取更多参考。