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的数据

  • 相关阅读:
    SVN中trunk、branches、tag的使用
    svn建立分支和svn代码合并的操作方法
    SVN分支的合并和同步
    iOS开发--即时通讯
    iOS 开发--开源图片处理圆角
    ios开发--网易滚动导航栏
    ios开发--高德地图SDK使用简介
    大型网站架构演变和知识体系
    Nginx配置文件nginx.conf中文详解
    nginx+apache+php+mysql服务器集群搭建
  • 原文地址:https://www.cnblogs.com/cuixiaomeng/p/13685548.html
Copyright © 2011-2022 走看看