zoukankan      html  css  js  c++  java
  • 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的数据

  • 相关阅读:
    内存初始化
    时钟初始化
    auto,register,static分析
    基本数据类型
    LED驱动简单设计
    核心初始化程序
    核心初始化基本介绍
    链接器脚本
    !带有指针的类和struct赋值的本质
    添加thrust的库后出错
  • 原文地址:https://www.cnblogs.com/cuixiaomeng/p/13685548.html
Copyright © 2011-2022 走看看