springboot @Autowired注入为null

读取 application-dev.yml 文件,如果是有多个 application.yml 文件请指定路径

 

 

package com.nuctech.datasync.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:/application-dev.yml")
@ConfigurationProperties(prefix = "erpax")
public class ReadApplication {
    
    private  String driverClassName;

    public String getDriverClassName() {
        return driverClassName;
    }
 public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
}

下面是 @Autowired注入配置信息类,get属性时,出现空指针的问题。

 

 

只要加上@PostConstruct 并且 public static SyncMaterialUtil syncMaterial;

一定要public static 

@PostConstruct 
public void init() {
syncMaterial= this;
syncMaterial.read= this.read; 
}

这样加上之后,就可以就可以用  syncMaterial.read.getDriverClassName() 的方式取到。

package com.nuctech.datasync.util;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SyncMaterialUtil {
    
    @Autowired
    private  ReadApplication read;

    public static SyncMaterialUtil syncMaterial;
    
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        syncMaterial= this;
        syncMaterial.read= this.read;  
    }
     
    public static void main(String[] args) {
      System.out.println(syncMaterial.read.getDriverClassName());
    }
}

测试取到了application.yml的数据

 

posted @ 2020-09-17 15:42  春眠不觉笑  阅读(6679)  评论(0编辑  收藏  举报