注解 @Resource 【转】

在java代码中使用@Autowired或@Resource注解方式进行装配,这两个注解的区别是:@Autowired默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
   @Autowired
    privatePersonDao  personDao;//用于字段上
   @Autowired
    public voidsetOrderDao(OrderDao orderDao) {//用于属性的setter方法上
       this.orderDao = orderDao;
    }
@Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false。如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:
   @Autowired  @Qualifier("personDaoBean")
    privatePersonDao  personDao;

@Resource注解和@Autowired一样,也可以标注在字段或属性的setter方法上,但它默认按名称装配。名称可以通过@Resource的name属性指定,如果没有指定name属性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。
   @Resource(name=“personDaoBean”)
    privatePersonDao  personDao;//用于字段上

注意:如果没有指定name属性,并且按照默认的名称仍然找不到依赖对象时,@Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

 

 

步骤:

(1).修改beans.xml

Java代码

  1. 在java代码中使用@Autowired或@Resource注解方式进行装配。但我们需要在xml配置文件中配置以下信息:  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.            http://www.springframework.org/schema/context  
  8.            http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  9.           <context:annotation-config/>  
  10. </beans>  

 这个配置隐式注册了多个对注释进行解析处理的处理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
     注:@Resource注解在spring安装目录的lib\j2ee\common-annotations.jar

 

  <context:annotation-config/>  必不可少

1、@controller 控制器(注入服务)


用于标注控制层,相当于struts中的action层


2、@service 服务(注入dao)


用于标注服务层,主要用来进行业务的逻辑处理


3、@repository(实现dao访问)


用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件.


4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的 
<bean id="" class=""/>)


泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。


案例: 
<context:component-scan base-package=”com.*”> 
上面的这个例子是引入Component组件的例子,其中base-package表示为需要扫描的所有子包。 
共同点:被@controller 、@service、@repository 、@component 注解的类,都会把这些类纳入进spring容器中进行管理
原文:https://blog.csdn.net/m0_37626813/article/details/78558010?utm_source=copy 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值