在@Service 类中有几个用@Value 注释的字段。这些字段未正确填充并且为空。也许我忽略了一些东西,我在下面粘贴了相关的代码块。尝试了具有相同结果的替代选项 env.getProperty()。
输出中以下属性的值为空。
package com.project.service.impl;
import org.springframework.beans.factory.annotation.Value
@Service("aService")
@PropertySource(value="classpath:app.properties")
public class ServiceImpl implements Service{
private Environment environment;
@Value("${list.size}")
private Integer list1;
@Value("${list2.size}")
private Integer list2Size;
@Autowired
public ServiceImpl(StringRedisTemplate stringTemplate){
this.stringTemplate = stringTemplate;
logger.info("TESTING 123: "+list1);
}
// ...
}
@EnableWebMvc
@ComponentScan(basePackages = {"com.project.service","..."})
@Configuration
public class ServletConfig extends WebMvcConfigurerAdapter {
// ...
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] {
new ClassPathResource("app.properties")
};
propertyPlaceholderConfigurer.setLocations(resources);
propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyPlaceholderConfigurer;
}
}
最佳答案
字段注入(inject)发生在构造之后,因此出现 NullPointer 异常。解决方案是使用 @Value 注释构造函数参数,例如
public ServiceImpl(StringRedisTemplate stringTemplate, @Value("${list.size}" Integer list1, ..){}
关于spring - @Service 类中的 @Value 属性为 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297493/