@Autowired在内部类中不起作用 [英] @Autowired not working in inner class

查看:139
本文介绍了@Autowired在内部类中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内部类中有一个@Autowired的类.但是在执行时会引发Null Pointer Exception,而在外部类中自动连线时它会很好地工作

I have a class being @Autowired in inner class. But while executing it throws a Null Pointer Exception, whereas it works fine when Autowired in outer class

class outer {
   ...
   class inner {
       @Autowired
       private var somevar;
       private process () {
           somevar.someMethod();
   }
}

有人知道为什么这行不通吗? somevar.someMethod(); 行正在生成NPE.

Any idea why this is not working? somevar.someMethod(); line is generating NPE.

推荐答案

外部类管理内部实例创建的原因是否存在?例如,内部对象是否需要引用外部对象?如果是,则不能用它制作一个bean.内部类只有在静态的情况下才可以是bean.因此,您必须自己管理所有依赖项(创建依赖关系的代码应完成这项工作).

Is there any reason why the outer class manages the inner instance creation? For example does the inner object need a reference to the outer one? If yes, you cannot make a bean out of it. Inner classes can be beans only if they are static. So you have to manage all dependencies yourself (the code that creates it should finish the job).

如果不需要对外部实例的此类引用,则将内部类设为静态,使用@Component进行注释,并让spring进行其余的依赖项注入.

If there is no need for such a reference to the outer instance, make the inner class static, annotate with @Component and leave spring do the rest of the dependency injection.

这篇关于@Autowired在内部类中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆