依赖注入-构造方法注入


通过构造方法注入,就相当于给构造方法的参数传值。

一、编写CustomerDao接口

package com.yiidian.dao;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public interface CustomerDao {

	public void save();
}

二、编写CustomerDaoImp实现类

package com.yiidian.dao.impl;

import com.yiidian.dao.CustomerDao;
/**
 * @author http://www.yiidian.com
 *
 */
public class CustomerDaoImpl implements CustomerDao {
	
	@Override
	public void save() {
		System.out.println("CustomerDaoImpl被成功注入!");
	}

}

三、编写CustomerService接口

package com.yiidian.service;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public interface CustomerService {

	public void save();
}

四、编写CustomerServiceImpl实现类

package com.yiidian.service.impl;

import com.yiidian.dao.CustomerDao;
import com.yiidian.service.CustomerService;
/**
 * 
 * @author http://www.yiidian.com
 *
 */
public class CustomerServiceImpl implements CustomerService {
	private CustomerDao customerDao;

	//关键在这里,提供CustomerDao作为参数的构造方法,待会在配置文件进行注入
	public CustomerServiceImpl(CustomerDao customerDao) {
		super();
		this.customerDao = customerDao;
	}


	@Override
	public void save() {
		customerDao.save();
	}

}

五、配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
    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="customerDao" class="com.yiidian.dao.impl.CustomerDaoImpl"></bean>
	 
	 <bean id="customerService" class="com.yiidian.service.impl.CustomerServiceImpl">
	 	<!-- 
	 	    index:代表构造方法参数的索引,0代表第一个参数,以此类推
	 	    ref: 代表引用另一个bean对象
	 	 -->
	 	<constructor-arg index="0" ref="customerDao"></constructor-arg>
	 </bean>
    
</beans>

六、测试

package com.yiidian.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yiidian.service.CustomerService;

/**
 * @author http://www.yiidian.com
 * 
 */
public class Demo1 {

	@Test
	public void test1() {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerService customerService = (CustomerService)context.getBean("customerService");
		customerService.save();
	}

}

七、运行结果

 

源码下载:http://pan.baidu.com/s/1bpxv8Ur