1、MyEclipse新建Web Project
2、下载SpringFramework,解压后到lib目录下找到spring-beans-3.2.2.RELEASE.jar,spring-context-3.2.2.RELEASE.jar,spring-context-support-3.2.2.RELEASE.jar,spring-core-3.2.2.RELEASE.jar,spring-expression-3.2.2.RELEASE.jar,分别添加到WEB-INF/lib下面,然后到网上下载commons-logging-1.1.1.jar,同样添加到该目录
3、新建包:com.liu.spring.dao,分别建立接口和实现类
//
package com.liu.spring.dao;
public interface IHelloDao {
public void sayHello();
}
//
package com.liu.spring.dao;
public class HelloDaoImpl implements IHelloDao {
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("say hello.......");
}
}
新建包:com.liu.spring.service,分别建立接口和实现类
// IHelloService
package com.liu.spring.service;
public interface IHelloService {
public void sayHello();
}
//
package com.liu.spring.service;
import com.liu.spring.dao.HelloDaoImpl;
import com.liu.spring.dao.IHelloDao;
public class HelloServiceImpl2 implements IHelloService {
private IHelloDao helloDao;
public IHelloDao getHelloDao()
{
return this.helloDao;
}
// 注意setter方法
public void setHelloDao(IHelloDao hellodao)
{
this.helloDao = hellodao;
}
public void sayHello()
{
helloDao.sayHello();
}
}
4、建立spring配置文件,分别为spring.xml,spring-dao.xml,spring-service.xml
// spring-dao.xml
<bean id="helloDao"class="com.liu.spring.dao.HelloDaoImpl" scope="singleton"lazy-init="default"></bean>
// spring-service.xml
<bean id="helloServiceImpl"class="com.liu.spring.service.HelloServiceImpl" scope="singleton"lazy-init="false">
<property name="helloDao"ref="helloDaoImpl"/>
// spring.xml
5、编写测试程序
新建包:com.liu.spring.test,新建一个包含main函数的java类
public static void main(String[] args) {
// 容器创建,实例化容器
ApplicationContext context = newClassPathXmlApplicationC
IHelloService helloService =context.getBean("helloServiceImpl",HelloServiceImpl.class);
helloService.sayHello();
}