2017-08-30 134 views
-1

我正在嘗試使用@Value註釋並自動填充屬性文件中的變量,但沒有運氣。值未被設置並且爲空。在構造對象之後發生Spring Boot - @Value返回null

taskService.java

@Service 
public class TaskService { 
    @Value("${a}") 
    String aa; 

    public final RestTemplate restTemplate; 

    public TaskService(RestTemplateBuilder restTemplateBuilder){ 
     System.out.println("----------xxxxxxxxxxx-------------" +aa); 
     this.restTemplate = restTemplateBuilder.build(); 
    } 

    public Task getTask(int taskId) throws TaskDoesNotExistException{ 
    try { 
     return this.restTemplate.getForObject("/tasks/{taskId}", Task.class, 
     taskId); 
    } catch (HttpClientErrorException e) { 
     if(e.getRawStatusCode() == 404) 
      throw new TaskDoesNotExistException("Task not found", e); 
    } 
    return null; 
} 
} 

eventhandler.java

@Component 
@RepositoryEventHandler(Application.class) 
public class ApplicationRepositoryEventHandler { 

@Autowired 
TaskService taskService; 

@HandleBeforeCreate 
public void handleApplicationCreate(Application application) throws 
TaskDoesNotExistException{ 
    for (Integer taskId: application.getTasks()){ 
     taskService.getTask(taskId); 
    } 
} 

}

+1

請[編輯]你的問題,以顯示你如何獲得有此問題的'TaskService'實例。 – Kenster

+0

嗨ochi,在哪裏使用@Configuration註解..我已經嘗試在服務類中,仍然返回空值 – user7700138

+0

值構造函數完成後注入。只需在構造函數參數中添加@Value(「$ {a}」)String aa'。 –

回答

1

字段注入。
請參閱https://stackoverflow.com/a/6336013/1544715
只需通過構造函數連同testTemplateBuilder一起注入aa
一般而言,您應該避免使用字段注入,或者至少嘗試使用每種類型的注入類型。

0

首先檢查您的屬性文件是否已加載,通常在輸出日誌開始時,您應該看到屬性文件的名稱。

然後在您的某個配置文件中配置以下bean(如果尚未完成)。這個bean在@Value中解析'$ {}'。

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

然後使用你正在做的方式,它應該解決property.And確保,TaskService bean實際加載(組件掃描包應該包含這個類)

雖然我通常使用上述方法,還有另外一種方法,你可能需要檢查(僅供參考,上面應該工作)

@Autowired 
private Environment env 

然後使用屬性任何需要的地方

env.getRequiredProperty(「some.property」) 
+0

嗨蘇里亞,我已經在配置中添加了PropertySource bean,並更新了下面的代碼。但是,返回空值。我是新來這個世界..請讓我知道,如果有什麼錯在這裏... – user7700138

+0

''' @Service @Component @ComponentScan 公共類TaskService { @Value(「$ {一:」5 '}「) String aa; public RestTemplate restTemplate; public TaskService(RestTemplateBuilder restTemplateBuilder){this.restTemplate = restTemplateBuilder.build(); System.out.println(「---------- xxxxxxxxxxx -------------」+ aa); } ''' – user7700138

+0

在ApplicationRepositoryEventHandler中,你確定taskservice(autowured)attr不爲null嗎?確保bean已加載。 – surya