英文:
@Autowired dosn't work into one controller in other method of the same controller works fine
问题
@Autowired在我将新的@RequestMapping方法添加到控制器中时突然停止工作。为什么我不明白。当我尝试使用这个新方法时,所有@Autowired接口都变为null。当我在其他方法中使用其他@RequestMapping时,一切都正常工作。
第一张图片显示了当我尝试使用新的@RequestMapping时,所有@Autowired类都为null。
这是我使用其他@RequestMapping时的情况,一切都正常工作。这是一个Spring Rest Api应用程序。我以前从未遇到过这种情况。是什么导致应用程序表现出这种行为。
英文:
@Autowired suddenly stop working when I added new @RequestMapping method into controller. Why I don't understand it. When I try to use this new method all @Autowired interface become null. When I use other @RequestMapping into other method all works perfectly.
First Image shows all @Autowired class is null when I try to use new @RequestMapping.
This I use other @RequestMapping all works perfectyl. This is spring Rest Api application. I've not encountered this things before. What might be behaving application like this.
答案1
得分: 6
Spring按以下方式创建您的控制器:
- 创建一个实例
- 注入
@Autowired
依赖项 - 使用代理将此实例包装起来,该代理处理注释,如
@PreAuthorize
或@Transactional
,然后将调用委托给真实实例。
由于Spring使用的代理库(CGLIB)以及通常的Java语言本身的性质,只允许重写public
方法。从您的示例中看,这是有道理的。
您的失败方法带有@PreAuthorize
注解,而且是private
,这意味着:它在代理上被调用,而代理没有注入的依赖项,因为通常它会委托给真实实例。但是,因为它是一个private
方法,CGLIB和Java不能这样做。
> 顺便说一下:从您的屏幕截图中可以看出,两次调用中的this
变量是不同的。
英文:
Spring creates your controller in the following manner:
- Create an instance
- Inject
@Autowired
dependencies - Wrap this instance with a Proxy, which handles the annotations, like
@PreAuthorize
or@Transactional
, and then delegates the call to the real instance.
Due to the nature of the proxy library Spring is using (CGLIB) and also generally the java language itself. It is only allowed to overwrite public
methods. Which, when looking at your example, makes sense.
Your method which is failing is annotated with @PreAuthorize
and.... it is private
, meaning: It was invoked on the proxy, and the proxy doesn't have the injected dependencies, because normally it would delegate to the real instance. But because it is a private
method, cglib and java can't do that.
> By the way: When looking at your screenshots you can see that the this
variable is different in both of your calls.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论