加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:38:58 所属栏目:大数据 来源:网络整理
导读:在@Service类中有几个用@Value注释的字段.这些字段未正确填充并且为空.也许我忽略了一些事情,我已经粘贴了下面的相关代码块.尝试了具有相同结果的替代选项env.getProperty(). 输出中以下属性的值为null. package com.project.service.impl;import org.spring

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

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

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;
    }
}
最佳答案
现场注入在构造之后发生,因此出现NullPointer异常.解决方案是使用@Value注释构造函数参数,例如

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读