首页 > @Resource作用

@Resource作用

@Resource
public interface MyObjectMapperExt extends MyObjectMapper {

 // TODO 
}

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

@Autowired
private MyObjectMapperExt myObjectMapperExt;

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


@Resource 注解式声明,你没有声明使用@Autowired找不到bean
可以简单的这么理解,一个叫spring的资源池,你要使用@Resource @Controller 等方法往池里做声明,就放进去了
使用@Autowired @Named 等方法从里面取出来


统一交给spring管理


@Resource
表示该bean交由spring容器来管理,一般情况下会将resource写在类或者接口的实现类上,而不是直接写在接口上。让spring容器管理的意思就是你想要实例化该类的时候,spring会自动帮你创建对象。

@Autowired
表示该属性(一般写在属性或者set方法上)让spring来自动注入。只有spring容器中有该资源(加了resource的bean当作一个资源对待)的话,spring才可以给你自动注入。spring容器中没有该资源时你再自动注入肯定找不到资源报错。

恰当而又不恰当的例子
火车站有个包寄存器(Spring容器),你想将你的包寄存到容器中。你就在包上贴了个@Resource标签,工作人员给你一个小条,表示该资源属于你。当你想拿包(获取该资源)的时候,你可以拿着小条(@Autowired)去包寄存器中找该资源。
如果你的包确实寄存在容器里了,那就根据你的小条给你包。
如果你没有把包寄存到容器里,还想问工作人员要包,那就报错。你就开始了和工作人员的决斗中。。。。。。。。。。。。。。
Spring是很正直的,有就给你,没有就是没有,没有资源的情况下,你再问我要。我就给你报错!!!
PS:感觉举的例子好乱,自己理解去吧。


/**
 * 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上面也是有问题的吧 应该放在实现类上面


第一个接口不加@Resource就不会把该接口的实现让spring管理,所以后面引用到该接口的地方注入都会失败

【热门文章】
【热门文章】