项目里@Autowired和@Value失效及原因

2019-10-06  本文已影响0人  桂老七

最近做个项目,遇到一个依赖注入的问题:
一个类A调用另一个类B的实例的时候采用new方法新建,但被调用类B里面@Value和@Autowired注解都没用了。 导致报空指针异常。

知识点:

@Autowired相当于setter,在注入之前,对象已经实例化,是在这个接口注解的时候实例化的;
而new只是实例化一个对象,而且new的对象不能调用注入的其他类

代码:

当时写了两个类:

FileListen //监听逻辑(入口函数)
MyFileLister  //监听触发的内容

实际运行时发生了空指针异常且@Value修饰的变量为null

类A:

@Component
@Slf4j
public class MyFileLister extends FileAlterationListenerAdaptor {
    //实际运行时这里失效了
    @Value("${fileNameIPUStart}")
    private Integer fileNameIPUStart;
    //实际运行时这里失效了
    @Value("${fileNameIPUEnd}")
    private Integer fileNameIPUEnd;
    //实际运行时这里失效了
    @Autowired
    QAService qaService;
    ...

}

类B:

@Configuration
public class FileListen implements CommandLineRunner {

    @Value("${fileStartURL}")
    private  String baseStartURL;

    @Value("${fileEndURL}")
    private  String baseEndURL;

    @Value("${fileListenInterval}")
    private  Integer fileListenInterval;

    private FileAlterationObserver observer;
    private FileAlterationMonitor monitor;
    private FileAlterationMonitor monitorOld;
    //这里不能用new来创建实例!!!
    private MyFileLister myFileLister = new MyFileLister();
    ...

上面的private MyFileLister myFileLister = new MyFileLister();应该改成

@Autowried
MyFileLister myFileLister

new的对象不能调用注入的其他类。

相关网帖

https://blog.csdn.net/p358278505/article/details/78404828

PS:最近应该补补Spring基础知识了

上一篇 下一篇

猜你喜欢

热点阅读