(一)Spring的注入类型
1、setter方法注入(常用,掌握)
2、构造方法注入(了解)
3、接口方法注入(了解)
(二)setter方法注入(通过查看Spring文档)
<bean id="exampleBean" class="examples.ExampleBean"> <!-- setter injection using the nested ref element --> <property name="beanOne"> <ref bean="anotherExampleBean"/> //其中<property name="beanOne">就是表示通过setBeanOne()方法注入 </property> <!-- setter injection using the neater ref attribute --> <property name="beanTwo" ref="yetAnotherBean"/> //这是简化写法 <property name="integerProperty" value="1"/> //简单属性传值,使用value(比较少用) </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; //setter方法 public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } //setter方法 public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } }
(二)使用构造方法注入
这种方式的注入是指带有参数的构造函数注入,看下面的例子,我创建了两个成员变量SpringDao和User,但是并未设置对象的set方法,所以就不能支持第一种注入方式,这里的注入方式是在SpringAction的构造函数中注入,也就是说在创建SpringAction对象时要将SpringDao和User两个参数值传进来:
- public class SpringAction {
- //注入对象springDao
- private SpringDao springDao;
- private User user;
- public SpringAction(SpringDao springDao,User user){
- this.springDao = springDao;
- this.user = user;
- System.out.println("构造方法调用springDao和user");
- }
- public void save(){
- user.setName("卡卡");
- springDao.save(user);
- }
- }
在XML文件中同样不用<property>的形式,而是使用<constructor-arg>标签,ref属性同样指向其它<bean>标签的name属性:
- <!--配置bean,配置后该类由spring管理-->
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <!--(2)创建构造器注入,如果主类有带参的构造方法则需添加此配置-->
- <constructor-arg ref="springDao"></constructor-arg>
- <constructor-arg ref="user"></constructor-arg>
- </bean>
- <bean name="springDao" class="com.bless.springdemo.dao.impl.SpringDaoImpl"></bean>
- <bean name="user" class="com.bless.springdemo.vo.User"></bean>
解决构造方法参数的不确定性,你可能会遇到构造方法传入的两参数都是同类型的,为了分清哪个该赋对应值,通过设置index来区分。
下面是设置index,就是参数位置:
- <bean name="springAction" class="com.bless.springdemo.action.SpringAction">
- <constructor-arg index="0" ref="springDao"></constructor-arg>
- <constructor-arg index="1" ref="user"></constructor-arg>
- </bean>