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>
上面代码下载: 点击下载