Spring入门案例

Spring入门案例

 

1. 导入两个jar包(在spring-framework-2.5.6文件内)

  (1)commons-logging.jar

  (2)spring.jar

 

2.两个接口,两个实现类,一个测试类,一个配置文件

 接口:AccountDaoIf.java,AccountServiceIf.java

实现类:AccountDao.java,AccountService.java

测试类:Test.java

配置文件:bean.xml

 

具体路径如图所示:

 

 

3.接口及实现类代码

(1)AccountDaoIf.java

package first;

public interface AccountDaoIf {
         //两种方法表示存款和取款
	public void withdraw();
	public void deposit();
}


 

 

 

 

 

 

 

 

 

 

 

 

 

 

(2)AccountDao.java

package first;

public class AccountDao implements AccountDaoIf {

	public void deposit() {
     System.out.println("deposit!");
		
	}

	public void withdraw() {
      System.out.println("withdraw!");
	}

}

 

(3) AccountServiceIf.java

package first;

public interface AccountServiceIf {
	//交易方法
	void transfer();
}


 

(4)AccountService.java
package first;

public class AccountService implements AccountServiceIf {

	private AccountDaoIf dao;	
	public void transfer() {
		System.out.println("transation begin");
		dao.withdraw();
		dao.deposit();
		System.out.println("transation commit");
	}
	//dao通过set方法注入
	public void setDao(AccountDaoIf dao){
		this.dao=dao;
	}
}


4.配置文件代码(通过配置文件实例化对象)
<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
			"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>

	<bean id="dao" class="first.AccountDao" />
	<bean id="service" class="first.AccountService">
		<property name="dao">
			<ref bean="dao" />
		</property>
	</bean>
</beans>



 
5.测试类
test.java
package test;
import first.AccountServiceIf;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Test {
	public static void main(String[] args) {
		ClassPathResource resource=new ClassPathResource("bean.xml");
		XmlBeanFactory factory =new XmlBeanFactory(resource);
		AccountServiceIf service =(AccountServiceIf) factory.getBean("service");
		service.transfer();
	}
}

 

 

6.运行结果:

 

 
 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值