使用Eclipse 开发Spring入门程序

1、使用Eclipse创建Web应用并导入JAR包

首先使用Eclipse创建一个Web应用(项目),将Spring的4个基础包和第三方依赖包commons-logging-1.2.jar复制到WEB-INF/lib目录中。
JAR包下载方式:http://t.csdn.cn/oLwgv

在这里插入图片描述

2、创建接口TestDao

Spring解决的是业务逻辑层与其他各层的耦合关系,因此它将面向接口编程的思想贯穿整个系统应用。

  • 表示层(Web)
  • 业务逻辑层(Service)
  • 持久层(Dao)

(Spring不是替代上述功能,而是整合,为上述的每一层提供技术支持。)

在src目录下创建一个dao包,并在dao包中创建接口TestDAO,在接口中定义一个sayHello方法,代码如下:

package dao;

//接口TestDao
public interface TestDao {
	
	//定义方法
	public void sayHello();
}

3、创建接口TestDao的实现类TestDaoImpl

在dao包下创建TestDao的实现类TestDaoImpl,代码如下:

package dao;

//创建类,实现接口
public class TestDaoImpl implements TestDao{

	@Override
	public void sayHello() {
		// TODO Auto-generated method stub
		System.out.println("hello, you've better study harder!");
	}
}

4、创建配置文件applicationContext.xml

在src目录下创建Spring的配置文件applicationContext.xml,并在该文件中使用实现类TestDaoImpl创建一个id为test的Bean,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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-4.3.xsd">
       
       <!-- 将制定类配置给Spring,让Spring创建其实例对象 -->
    <bean id="test" class="dao.TestDaoImpl"></bean>
 </beans>

配置文件名可以自定义,但是习惯上命名为applicationContext.xml,有时候也命名为beans.xml。
配置文件信息不需要手写,可以从Spring的帮助文档中复制,步骤如下:

1、打开文件:spring-framework-4.3.6.RELEASE>docs>spring-framework-reference>html>index.html

在这里插入图片描述

2、点击Configuration metadata,复制下面的约束信息

在这里插入图片描述

3、 设置版本号

在这里插入图片描述

5、创建测试类

在src目录下创建一个test,并在test包中创建Test类,代码如下:

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.TestDao;

//测试类
public class Test {

	public static void main(String[] args) {
		//1、初始化Spring容器,加载配置文件
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2、通过容器获取testDao的实例
		TestDao tt = (TestDao) applicationContext.getBean("test");	//test配置文件中的id 
		//3、调用实例方法
		tt.sayHello();
	}

}

在执行上述main方法后,控制台会输出"hello, you’ve better study harder!"。在上述main方法中并没有使用new运算符创建TestDaoImpl类的对象,而是通过Spring容器来获取实现类对象,这就是IoC的工作机制。

  • 12
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值