spring依赖注入之构造器方式注入
public class StudentDao implements IStudentDao { public void saveStudent() { System.out.println("成功保存一个学生信息"); }}
?
2. 服务层
public class StudentService implements IStudentService { private IStudentDao studentDao; private String id; public StudentService(IStudentDao studentDao,String id){ this.studentDao = studentDao; this.id = id; } public void saveStudent() { studentDao.saveStudent(); System.out.print(",ID为:"+id); }}
?
3. spring配置
<bean id="studentDao" type="com.wch.dao.IStudentDao" ref="studentDao" /> <constructor-arg index="1" value="123456" type="java.lang.String"></constructor-arg> </bean>
?
?
?注:
用 ?public class TestSpringBuild extends TestCase{ private AbstractApplicationContext ctx = null; @Before public void setUp() throws Exception { //ctx = new ClassPathXmlApplicationContext("bean.xml"); ctx = new FileSystemXmlApplicationContext("classpath:bean.xml"); } @After public void tearDown() throws Exception { ctx.close(); } @Test public void testBuild(){ StudentService studentService = (StudentService)ctx.getBean("studentService"); studentService.saveStudent(); }}