SpringIOC的HelloWorld

一、建立Java工程,导入spring ioc必须的jar包

注意:commons-logging-1.2.jar这个包是来自于apache的日志包。

二、编写Dao接口和实现类

CustomerDao接口:

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

	public void save();
}

CustomerDaoImpl实现类:

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("把客户数据保存到mysql数据");
	}

}

三、在src目录下建立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">

	<!-- 创建 CustomerDaoImpl对象-->
	<bean id="customerDao" class="com.yiidian.dao.impl.CustomerDaoImpl"></bean>
    
</beans>

四、编写测试代码

package com.yiidian.test;

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

import com.yiidian.dao.CustomerDao;
/**
 * @author http://www.yiidian.com
 *
 */
public class Demo1 {
	
	@Test
	public void test1(){
		//1.初始化SpringIOC容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2.从IOC容器取出对象
		CustomerDao customerDao = (CustomerDao)ac.getBean("customerDao"); 
		System.out.println(customerDao);
	}
}

四、运行Demo测试类的test方法,结果为:

 

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

热门文章

优秀文章