Spring 依赖注入 @Autowired @Inject

想到哪说到哪。

Spring的依赖注入有三种方式:set注入,构造方法注入,接口注入,经常用的是前两者。

具体的实现可以通过xml+代码的方式(set注入,构造方法注入,接口注入)和注解方式来进行,其实注解只是为了简化xml+代码的方式。

但不管是xml方式还是注解方式在xml中(applicationContext.xml)都必须写<bean id="***" class="***"/>

xml+代码(set注入):

applicationContext.xml

<bean id="t001Service" class="tsr.or.service.impl.T001ServiceImpl"/>
            <bean id="t001Action" class="tsr.or.action.T001Action">
            <property name="t001Service" ref="t001Service"></property>
        </bean>

在代码中:

    private T001Service t001Service;
    public void setT001Service(T001Service t001Service) {
        this.t001Service = t001Service;
    }

使用这种方式,set方法(setT001Service)是必须的


xml+代码(构造方法注入):

applicationContext.xml

          <bean id="t001Service" class="tsr.or.service.impl.T001ServiceImpl"/>
          <bean id="t001Action" class="tsr.or.action.T001Action">
            <constructor-arg index="0" ref="t001Service"></constructor-arg>
          </bean>

在代码中:

    private T001Service t001Service;
    public T001Action(T001Service t001Service) {
        this.t001Service = t001Service;
    }

xml+代码(接口注入):

省略,不写了


注解方式:

applicationContext.xml

<bean id="t001Service" class="tsr.or.service.impl.T001ServiceImpl"/>

        在代码中:

    @Autowired
    private T001Service t001Service;

   public void setT001Service(T001Service t001Service) {
        this.t001Service = t001Service;
    }

     或者是

    @Inject
    private T001Service t001Service;

@Autowired和@Inject的作用是一样的,只不过一个是spring提供的,一个是J2EE提供,用哪个都可以的。

但是如果用@Autowired的话,在代码中要有set方法,而@Inject不需要set方法。

PS:如果在代码中使用了@Autowired又不想写set方法,也是有办法的。办法有两个:第1个是,在applicationContext.xml中加上这句话<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />,在代码中使用@Autowired就不需要set方法了。

第2个是,spring提供了一个扫描的方法也是在applicationContext.xml中使用context:component-scan base-package="tsr.or.service.impl"/>来代替<bean id="t001Service" class="tsr.or.service.impl.T001ServiceImpl"/>,这样就不需要set方法了。另外尽量使用扫描的方法,否则要注入的bean太多了,需要一个一个写入applicationContext.xml中,太繁琐了。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值