依赖注入-setter方法注入
通过无参构造函数+setter方法注入。
一、编写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作为参数的setter方法,待会在配置文件进行注入
public void setCustomerDao(CustomerDao customerDao) {
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">
<!--
name:代表CustomerServiceImpl中的setter方法名称
ref:代表引用另一个bean对象,即CustomerDaoImpl对象
-->
<property name="customerDao" ref="customerDao"></property>
</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();
}
}
七、运行结果
热门文章
优秀文章