2017-08-30 133 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