Spring的autowire

问题描述

如果一个bean里有很多属性,每个属性都要手动加property节点显式注入属性值,就很麻烦。

解决方案

让IOC容器自动为bean指定引用

方法一:在XML配置文件里实现autowire(不会用的多,容易出错)

autowire默认值为no。
1.byName:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为byName,而该bean包含master属性(同时提供setMaster(..)方法),Spring就会查找名为master的bean定义,并用它来装配给master属性。

<bean id="userDao1" class="com.dao.impl.UserDaoImpl" scope="prototype">
    <property name="daoId" value="1"></property>
</bean>

<bean id="userDao2" class="com.dao.impl.UserDaoImpl" scope="prototype">
    <property name="daoId" value="2"></property>
</bean>

<bean id="userService" class="com.service.UserService" autowire="byName">

test类,IOC容器根据方法名getUserDao1,自动转为属性名userDao1,去XML里查找对应bean的id。

ApplicationContext factory = new ClassPathXmlApplicationContext("beans.xml");

UserService service = (UserService) factory.getBean("userService");

System.out.println(service.getUserDao1().toString());

2.byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置dependency-check=”objects”让Spring抛出异常。
constructor与autodetect省略。
只要将对应的UserDaoImpl删去一个就可以。

<bean id="userDao1" class="com.dao.impl.UserDaoImpl" scope="prototype">
    <property name="daoId" value="1"></property>
</bean>

<bean id="userService" class="com.service.UserService" autowire="byName">

如果所有的bean都用同一种autowire,则可以使用beans的属性:default-autowire。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
           default-autowire="byName">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值