java - @Resource作用
大家讲道理
大家讲道理 2017-04-18 09:38:48
0
5
611
@Resource
public interface MyObjectMapperExt extends MyObjectMapper {

 // TODO 
}

为什么在这个地方不加@Resource的时候,在另外一个地方注入MyObjectMapperExt会失败?

@Autowired
private MyObjectMapperExt myObjectMapperExt;

会注入失败,提示无法注入。是什么原因?而且@Resource是mybatis自动生成的。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(5)
阿神
/**
 * The Resource annotation marks a resource that is needed
 * by the application.  This annotation may be applied to an
 * application component class, or to fields or methods of the
 * component class.  When the annotation is applied to a
 * field or method, the container will inject an instance
 * of the requested resource into the application component
 * when the component is initialized.  If the annotation is
 * applied to the component class, the annotation declares a
 * resource that the application will look up at runtime. <p>
 *
 * Even though this annotation is not marked Inherited, deployment
 * tools are required to examine all superclasses of any component
 * class to discover all uses of this annotation in all superclasses.
 * All such annotation instances specify resources that are needed
 * by the application component.  Note that this annotation may
 * appear on private fields and methods of superclasses; the container
 * is required to perform injection in these cases as well.
 *
 * @since Common Annotations 1.0
 */
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)

這是@Resource注解的介绍,@Resource用在字段或者方法上的时候,Spring会从容器里面寻找需要的类型Bean,@Resource用在類別上的時候,Spring會把當前類別當作資源放入Spring容器。

@Autowired注解表示让Spring容器自动注入这个bean,@Resource表示把当前注解的类交给Spring容器管理,你不使用@Resource註解,Spring容器就不會載入這個類型的bean,需要注入的時候自然就報錯了

你把@Resource用在interface上面也是有問題的吧 應該放在實作類別上面

刘奇

統一交給spring管理

左手右手慢动作

第一個介面不加@Resource就不會把該介面的實作讓spring管理,所以後面引用到該介面的地方注入都會失敗

伊谢尔伦

@Resource 註解式聲明,你沒有聲明使用@Autowired找不到bean
可以簡單的這麼理解,一個叫spring的資源池,你要使用@Resource @Controller 等方法往池裡做聲明,就放進去了
使用@Autowired @Named 等方法從裡面取出

Ty80

@Resource
表示該bean交由spring容器來管理,一般情況下會將resource寫在類別或介面的實作類別上,而不是直接寫在介面上。讓spring容器管理的意思就是你想要實例化該類別的時候,spring會自動幫你建立物件。

@Autowired
表示該屬性(一般寫在屬性或set方法上)讓spring來自動注入。只有spring容器中有該資源(加了resource的bean當作一個資源對待)的話,spring才可以為你自動注入。 spring容器中沒有該資源時你再自動注入肯定找不到資源報錯。

恰當而又不恰當的例子
火車站有個包寄存器(Spring容器),你想將你的包寄存到容器中。你就在包包上貼了個@Resource標籤,工作人員給你一個小條,表示該資源屬於你。當你想拿包(取得該資源)的時候,你可以拿著小條(@Autowired)去包寄存器中找該資源。
如果你的包包確實寄存在容器裡了,那就根據你的小條給你包包。
如果你沒有把包包寄存到容器裡,還想問工作人員要包,那就報錯。你就開始了和工作人員的決鬥。 。 。 。 。 。 。 。 。 。 。 。 。 。
Spring是很正直的,有就給你,沒有就是沒有,沒有資源的情況下,你再問我要。我就給你報錯! ! !
PS:感覺舉的例子好亂,自己懂去吧。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板