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的數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM