SpringBoot @AutoWired Null

在调用工具类时,若工具类中含有@Autowired注解,这此工具类对象必须同样使用@Autowired注解,否则工具类中的Spring注入的对象都为空值,这里的HadoopTest就是这样

比如MyConfig类是

配置层
@Component
@ConfigurationProperties(prefix = "project")
public class MyConfig {
    private String version;
    private String name;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


HadoopTest类引用了MyConfig
public class HadoopTest {

    @Autowired
    MyConfig myConfig; //这里用了注入,所以controller层的test类中  HadoopTest hadoopTest=new HadoopTest();是无效的

    public void getName() {
        System.out.println(myConfig.getName());
    }

}

Controller中
@RestController
public class test {
    HadoopTest hadoopTest=new HadoopTest();

    @GetMapping("hello")
    public void hello() {
        hadoopTest.getName();
    }
}

这样在System.out.println(myConfig.getName());中是找不到myconfig的,我们应该改成

配置层
@Component
@ConfigurationProperties(prefix = "project")
public class MyConfig {
    private String version;
    private String name;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


HadoopTest类引用了MyConfig
@Component
public class HadoopTest {

    @Autowired
    MyConfig myConfig;

    public void getName() {
        System.out.println(myConfig.getName());
    }

}

Controller类中
@RestController
public class test {
   @Autowired
    HadoopTest hadoopTest;

    @GetMapping("hello")
    public void hello() {
        hadoopTest.getName();
    }
}

或者是

配置层
@Compoment
@ConfigurationProperties(prefix = "project")
public class MyConfig {
    private String version;
    private String name;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

HadoopTest类引用了MyConfig
public class HadoopTest {

    MyConfig myConfig=new Myconfig;

    public void getName() {
        System.out.println(myConfig.getName());
    }

}

Controller类中
@RestController
public class test {
    HadoopTest hadoopTest=new HadoopTest();

    @GetMapping("hello")
    public void hello() {
        hadoopTest.getName();
    }
}

也就是一条逻辑线上,HadoopTest注入了MyConfig,那么在test中必须也是注入而不是new,原因以后在补充。
补充:1.在第三种情况中,虽然MyConfig被注释了,但是只要不去注入它就没关系。

posted @ 2018-11-26 16:50  周景白炎  阅读(1340)  评论(0编辑  收藏  举报