簡體   English   中英

Spring 引導@Value 注釋返回 null

[英]Spring boot @Value annotation returning null

我有一個 java class,如下所示,它正在創建一個帶有連接和讀取超時的 rest 模板,並且還會創建一個在發生連接和讀取超時時執行重試的重試模板。 我正在從 application.properties 文件中讀取值,但由於某種原因,我得到了正在讀取的值的 null 值。我不知道我能做些什么來解決這個問題。 對此的任何建議將不勝感激。

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());
   }
}

應用程序屬性

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 結束

重試休息模板

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

}

Class Retry可能不受 Spring 管理。 Retry class 時添加 @Configuration。

@Configuration
public class Retry {
}

嘗試將@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用於構造函數 arguments:

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

除了@Value注解之外,還有其他方法可以獲取屬性值。 通過使用Environment接口的實例。

請按照以下步驟操作:

  1. Retry.java上添加@Component注釋
  2. Retry.java中的導入和自動裝配Environment

     import org.springframework.core.env.Environment @Autowired private Environment env;
  3. 從 env 獲取屬性的值。 例如,

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

該物業的價值還有其他幾種口味。 你可以看看這個

2件事:
1)正如其他人所說,添加配置
2)檢查您是否在為其創建 object 的任何 class 中使用 Retry as Autowired。 如果在實例化的 object 中使用任何 bean class,它將返回 null。

請在您的Retry.java中添加以下注釋

@Configuration
@PropertySource("classpath:application.properties")

並更改您的@Value注釋,如下所示

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

它應該工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM