spring – @Service类中的@Value属性为Null

前端之家收集整理的这篇文章主要介绍了spring – @Service类中的@Value属性为Null前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在@Service类中有几个用@Value注释的字段.这些字段未正确填充并且为空.也许我忽略了一些事情,我已经粘贴了下面的相关代码块.尝试了具有相同结果的替代选项env.getProperty().

输出中以下属性的值为null.

  1. package com.project.service.impl;
  2. import org.springframework.beans.factory.annotation.Value
  3. @Service("aService")
  4. @PropertySource(value="classpath:app.properties")
  5. public class ServiceImpl implements Service{
  6. private Environment environment;
  7. @Value("${list.size}")
  8. private Integer list1;
  9. @Value("${list2.size}")
  10. private Integer list2Size;
  11. @Autowired
  12. public ServiceImpl(StringRedisTemplate stringTemplate){
  13. this.stringTemplate = stringTemplate;
  14. logger.info("TESTING 123: "+list1);
  15. }
  16. // ...
  17. }
  18. @EnableWebMvc
  19. @ComponentScan(basePackages = {"com.project.service","..."})
  20. @Configuration
  21. public class ServletConfig extends WebMvcConfigurerAdapter {
  22. // ...
  23. @Bean
  24. public static PropertySourcesPlaceholderConfigurer properties() {
  25. PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
  26. Resource[] resources = new ClassPathResource[] {
  27. new ClassPathResource("app.properties")
  28. };
  29. propertyPlaceholderConfigurer.setLocations(resources);
  30. propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
  31. return propertyPlaceholderConfigurer;
  32. }
  33. }
@H_403_12@最佳答案
现场注入在构造之后发生,因此出现NullPointer异常.解决方案是使用@Value注释构造函数参数,例如

  1. public ServiceImpl(StringRedisTemplate stringTemplate,@Value("${list.size}" Integer list1,..){}

猜你在找的Spring相关文章