构造注入就是指在构造事例时,已经为其完成了依赖关系的初始化,因此在现实类中必须要有类的构造器才行,
这里我们构造了personserviceImpl的构造器:
public class PersonServiceImpl implements PersonService { private PersonDao personDao; private String name; public PersonServiceImpl(PersonDao personDao, String name) { this.personDao = personDao; this.name = name; } /* (non-Javadoc) * @see com.ncut.service.PersonService#save() */ public void save() { //System.out.println("这是personservice的实现类save()"); personDao.add(); System.out.println(name); } }其他的地方不改变就是在applicationContext.xml的配置文件中进行简单的配置:
<bean id="personService" class="com.ncut.service.PersonServiceImpl"> <constructor-arg index="0" type="com.ncut.dao.PersonDao" ref="personDao"></constructor-arg> <constructor-arg index="1" value="北方工业大学"></constructor-arg> </bean> <bean id="personDao" class="com.ncut.dao.PersonDaoImpl"></bean>
我们看到了<constructor-arg>这样的标签就知道这就是为构造器准备的,其中index索引是指构造器中的函数变量位置,ref则是依赖对象spring会自动找到配置文件中的对像名。