1、修改 PresonServiceImpl 类,代码如下:
![]()
package com.learn.service.impl;
import com.learn.dao.PresonDao;
import com.learn.service.PresonService;
public class PresonServiceImpl implements PresonService {
private PresonDao presonDao;
private String name;
public PresonServiceImpl(PresonDao presonDao, String name) {
this.presonDao = presonDao;
this.name = name;
}
/* (non-Javadoc)
* @see com.learn.service.impl.PresonService#save()
*/
@Override
public void save(){
System.out.println("name="+name);
presonDao.add();
}
}
2、xml 文件如下:
![]()
<?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.xsd">
<bean id="personDao" class="com.learn.dao.impl.PresonDaoImpl"></bean>
<bean id="personService" class="com.learn.service.impl.PresonServiceImpl">
<constructor-arg index="0" type="com.learn.dao.PresonDao" ref="personDao"></constructor-arg>
<constructor-arg index="1" value="博客"></constructor-arg>
</bean>
</beans>
constructor-arg:表示通过构造函数注入。index 属性值表示属性在构造函数中的位置,从零开始;type 表示属性类型,基础数据类型可以不用写,但是经检测spring4.0中class 数据类型也可以不写;ref 表示注入依赖对象,value 表示给基础数据注入值。
3、单元测试:
![]()
package junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.service.PresonService;
public class TestSpring {
@Test
public void initContainerSpring() {
//实例化spring容器 (使用类构造器实例化)
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("com//learn//spring//learn1.xml");
PresonService personService = (PresonService)ctx.getBean("personService");
personService.save();
}
}
注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果。