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.运行结果: