Loading

@Value值为null、#和$的区别

获取属性值

在springboot中通过PropertySources注解读取指定配置文件

@PropertySource(value = {"classpath:env.properties"}, encoding = "utf-8")

值为null

这个属性在env.properties中

@Value(value="${auth_bili}")
private String auth_bili;

但是debug的时候这个值显示为null

被调用类的上半部分是这样子的

@Component
public class BiliRequest implements Request {

    @Value(value="${auth_bili}")
    private String auth_bili;

    // TODO 修改构造函数
    private HttpHeaders _headers;

    private HttpEntity<String> formEntity;

    private Map<String, Object> maps;

    private RestTemplate restTemplate;

    public BiliRequest(){
        restTemplate = new RestTemplate();
    }
......

而调用这个类所生成的被调用类的实例用的是new biliRequest(),这一步导致@Value注解失效

应该在调用类中这么写

@Service(value = "ContentManagementService")
public class ContentManagementServiceImpl implements ContentManagementService {

    @Resource
    private UrlFactory urlFactory;

    @Resource
    private BiliRequest biliRequest;
......

不用new关键字,使用注解,通过spring框架的方式实例化,而不是jvm层面的实例化

在网上查到的@Value的其他原因

  • 调用类类没有加上@Component(或者@service等)
  • 用static或者final修饰
posted @ 2021-07-08 10:16  BigBender  阅读(149)  评论(0编辑  收藏  举报