@Autowired dosn't work into one controller in other method of the same controller works fine

huangapple go评论77阅读模式
英文:

@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.

@Autowired dosn't work into one controller in other method of the same controller works fine

First Image shows all @Autowired class is null when I try to use new @RequestMapping.

@Autowired dosn't work into one controller in other method of the same controller works fine

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按以下方式创建您的控制器:

  1. 创建一个实例
  2. 注入@Autowired依赖项
  3. 使用代理将此实例包装起来,该代理处理注释,如@PreAuthorize@Transactional,然后将调用委托给真实实例。

由于Spring使用的代理库(CGLIB)以及通常的Java语言本身的性质,只允许重写public方法。从您的示例中看,这是有道理的。

您的失败方法带有@PreAuthorize注解,而且是private,这意味着:它在代理上被调用,而代理没有注入的依赖项,因为通常它会委托给真实实例。但是,因为它是一个private方法,CGLIB和Java不能这样做。

> 顺便说一下:从您的屏幕截图中可以看出,两次调用中的this变量是不同的。

英文:

Spring creates your controller in the following manner:

  1. Create an instance
  2. Inject @Autowired dependencies
  3. 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.

huangapple
  • 本文由 发表于 2020年9月3日 14:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63717765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定