spring 使用注解注入bean

3 篇文章 0 订阅

学了两种使用注解注入bean的方式,按照网上提供的方法学习并整理的。


1、@Resource  2、@Autowired

首先要说明的是 spring的头文件,下面是一个比较全的头文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">


第一种使用介绍:

@Resource 默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入;是由J2EE提供,可以减少系统对spring的依赖,建议使用  ,可以书写标注在字段或者该字段的setter方法之上。

bean配置:

<context:annotation-config />
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean>
    <bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype">
      <!--  <property name="sqlMapClient">
           <ref bean="sqlMapClient"/>
       </property> -->
    </bean>

Java代码配置

a、标注在字段上

 @Resource(name="userService")
    private UserService userService;
b、标注在setter方法上

 @Resource(name="userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

说明:括号内 name="userService" 可以省去,系统会自动按照属性名寻找bean.如果配了name属性,系统会按照name所配的bean id 查找。放在 字段上时,set方法可以省去。

第二种使用介绍:

@Autowired:默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qualifier一起使用;可以书写标注在字段或者该字段的setter方法之上。

bean配置:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean>
<bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype"></bean>

Java 代码配置:

 @Autowired
    private UserService userService;

或者:

 @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


说明:@Autowired 放在 字段上时,set方法可以省去。

按照名称注入,bean按照上边即可。

Java代码配置:

@Autowired
    @Qualifier("userService")
    private UserService userServices;

或者 
 @Autowired
    public void setUserServices(@Qualifier("userService")UserService userService) {
        this.userServices = userService;
    }





       

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值