使用Spring框架开发的第一个实例

1、建立Java工程:spring_first

2、导入开发Spring需要的jar包(参考我的文章:构建Spring开发环境)

3、开发DAO层,代码如下:

com.spring.dao.UserDao

public interface UserDao {
	public void addUser(String username, String password);
}

com.spring.dao.impl.UserDao4MySqlImpl.java

public class UserDao4MySqlImpl implements UserDao {
	public void addUser(String username, String password) {
		System.out.println("UserDao4MySqlImpl.addUser()");
	}
}

com.spring.dao.impl.UserDao4OracleImpl.java

public class UserDao4OracleImpl implements UserDao {
	public void addUser(String username, String password) {
		System.out.println("UserDao4OracleImpl.addUser()");
	}
}

4、开发Service层

com.spring.service.UserService.java

public interface UserService {
	public void addUser(String username, String password);
}

com.spring.service.Impl.UserServiceImpl.java

public class UserServiceImpl implements UserService {

	private UserDao userDao;
// public UserServiceImpl(UserDao userDao) {
// 	this.userDao = userDao;
// }
	public void addUser(String username, String password) {
		userDao.addUser(username, password);
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}

5、提供applicationContext.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	     xmlns:aop="http://www.springframework.org/schema/aop"
	     xmlns:tx="http://www.springframework.org/schema/tx"
	     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
  
  <bean id="userDao4Mysql" class="com.spring.dao.UserDao4MySqlImpl"/>
  
  <bean id="usrDao4Oracle" class="com.spring.dao.UserDao4OracleImpl"/>
  
  <bean id="userManager" class="com.spring.service.UserServiceImpl">
  	<!-- 
   	<constructor-arg ref="userDao4Mysql"/>
   	 -->
   	<!--  
   	<constructor-arg ref="usrDao4Oracle"/>
   	 -->
   	 <property name="userDao" ref="usrDao4Oracle"/>
  </bean>
</beans>

上面代码下载: 点击下载 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值