Spring入门

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,分别建立接口和实现类

// IHelloDao 

package com.liu.spring.dao;

public interface IHelloDao {

public void sayHello();

}

// HelloDaoImpl

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();

}

// HelloServiceImpl

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"/>

 </bean>

// spring.xml

   <!--分别在不同的xml中定义不同类型的bean-->

   <importresource="spring-dao.xml"/>

   <importresource="spring-service.xml"/>

5、编写测试程序

新建包:com.liu.spring.test,新建一个包含main函数的java类

public static void main(String[] args) {

// 容器创建,实例化容器

ApplicationContext context = newClassPathXmlApplicationContext("spring.xml"); //路径是WEB-INF/classes

IHelloService helloService =context.getBean("helloServiceImpl",HelloServiceImpl.class);

helloService.sayHello();

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值