Spring Boot @Value注解返回空

时间:2019-10-22 22:13:53

标签: java maven spring-boot annotations spring-retry

我有一个Java类,如下所示,该类创建带有连接和读取超时的rest模板,还创建一个重试模板,该模板在发生连接和读取超时时执行重试。我正在从application.properties文件中读取值,但是由于某些原因,正在读取的值会得到空值。我不知道该如何解决。任何对此的建议将不胜感激。

public class Retry {

@Value("${read.Timeout.InMilliSeconds:-1}")
private Integer readTimeoutInMilliSeconds;

@Value("${connect.Timeout.InMilliSeconds:-1}")
private Integer connectTimeoutInMilliSeconds;

@Value("${backOff.Period.InMilliSeconds:-1}")
private Integer backOffPeriodInMilliSeconds;

@Value("${max.Attempts:-1}")
private Integer maxAttempts;

@Bean
public RestTemplate restTemplate() {

    RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
    return restTemplate;
}

private HttpComponentsClientHttpRequestFactory getClientHttpRequestFactory() {

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(readTimeoutInMilliSeconds);
    requestFactory.setConnectTimeout(connectTimeoutInMilliSeconds);
    return requestFactory;
}

@Bean
public RetryTemplate retryTemplate() {

    Map<Class<? extends Throwable>, Boolean> retryableExpressions = new HashMap<>();

    // connection and read timeouts
    retryableExpressions.put(ResourceAccessException.class, true);

    // 404
    retryableExpressions.put(RestClientException.class, false);

    SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(maxAttempts, retryableExpressions);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(backOffPeriodInMilliSeconds);

    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(simpleRetryPolicy);
    retryTemplate.setBackOffPolicy(backOffPolicy);

    return retryTemplate;
}

@Bean
public RetryRestTemplate retryRestTemplate() {
    return new RetryRestTemplate(
            restTemplate(),
            retryTemplate());
   }
}

application.properties

read.Timeout.InMilliSeconds=10000
connect.Timeout.InMilliSeconds=10000
backOff.PeriodInMilliSeconds=10000
max.Attempts=5

堆栈跟踪

Caused by: java.lang.NullPointerException: null
at com.beans.Retry.getClientHttpRequestFactory(Retry.java:43)
at com.beans.Retry.restTemplate(Retry.java:36)
at com.beans.Services.retryRestTemplate(Services.java:82)
at com.beans.Services$$EnhancerBySpringCGLIB$$819e8a9c.CGLIB$retryRestTemplate$3(<generated>)
at com.beans.Services$$EnhancerBySpringCGLIB$$819e8a9c$$FastClassBySpringCGLIB$$65931da6.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.beans.Services$$EnhancerBySpringCGLIB$$819e8a9c.retryRestTemplate(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 213 common frames omitted

以退出代码1完成的过程

RetryRestTemplate

public class RetryRestTemplate {

private RestTemplate restTemplate;
private RetryTemplate retryTemplate;

public RetryRestTemplate(RestTemplate restTemplate, RetryTemplate retryTemplate) {
    this.restTemplate = this.restTemplate;
    this.retryTemplate = this.retryTemplate;
}

public ResponseEntity getForEntity(URI uri, Class c) {
    return retryTemplate.execute(retryContext -> {
        System.out.println("Check");
        return restTemplate.getForEntity(uri, c);
    });
}

public ResponseEntity exchange(String url, HttpMethod get, HttpEntity headers, Class c) {
    return retryTemplate.execute(retryContext -> {
        return restTemplate.exchange(url, get, headers, c);
    });
}

public <T extends Object> ResponseEntity<T> postForEntity(String apiUrl, HttpEntity<Object> entityRequest, Class<T> responseClass) {
    return retryTemplate.execute(retryContext -> {
        return restTemplate.postForEntity(apiUrl, entityRequest, responseClass);
    });
}

}

4 个答案:

答案 0 :(得分:1)

Retry可能不是由Spring管理的。在Retry类上添加@Configuration。

@Configuration
public class Retry {
}

答案 1 :(得分:0)

尝试将@Value(...)移至相应的方法中作为输入参数,如下所示:

private HttpComponentsClientHttpRequestFactory getClientHttpRequestFactory(
    @Value("${read.Timeout.InMilliSeconds:-1}") Integer readTimeoutInMilliSeconds,
    @Value("${connect.Timeout.InMilliSeconds:-1}") Integer connectTimeoutInMilliSeconds) {
    ...
}

@Bean
public RetryTemplate retryTemplate(
    @Value("${backOff.Period.InMilliSeconds:-1}") Integer backOffPeriodInMilliSeconds,
    @Value("${max.Attempts:-1}") Integer maxAttempts) {
    ...
}

或者您也可以尝试为Retry创建一个构造函数,并使用@Value作为构造函数参数:

private Integer readTimeoutInMilliSeconds;
private Integer connectTimeoutInMilliSeconds;
private Integer backOffPeriodInMilliSeconds;
private Integer maxAttempts;

Retry(@Value("${read.Timeout.InMilliSeconds:-1}") Integer readTimeoutInMilliSeconds,
      @Value("${connect.Timeout.InMilliSeconds:-1}") Integer connectTimeoutInMilliSeconds,
      @Value("${backOff.Period.InMilliSeconds:-1}") Integer backOffPeriodInMilliSeconds,
      @Value("${max.Attempts:-1}") Integer maxAttempts) {
    this.readTimeoutInMilliSeconds = readTimeoutInMilliSeconds;
    this.connectTimeoutInMilliSeconds = connectTimeoutInMilliSeconds;
    this.backOffPeriodInMilliSeconds = backOffPeriodInMilliSeconds;
    this.maxAttempts = maxAttempts;
}

答案 2 :(得分:0)

@Value批注外,还有其他获取属性值的方法。通过使用Environment接口的实例。

请遵循以下步骤:

  1. @Component上添加Retry.java注释
  2. Environment导入并自动连线到Retry.java

    import org.springframework.core.env.Environment
    @Autowired
    private Environment env;
    
  3. 从env获取属性的值。例如,

    env.getProperty("read.Timeout.InMilliSeconds","-1");

该属性的价值还具有其他几种风味。您可以在this上签出。

答案 3 :(得分:0)

2件事:
1)正如其他人所说,添加配置
2)检查是否在为其创建对象的任何类中都使用“自动重试”。如果实例化的对象中使用了任何bean类,则它返回null。