最近离职一边找工作一边开始重新学习spring.以前学的都忘记了
做个例子放上来.就当自己的学习归纳了.省的老忘.
首先说下对spring的看法.spring主要提供的功能就是管理.降低层与层之间的耦合,它主要包含IOC(控制反转),Dependency Injection(依赖注入)AOP(面向切面编程),以及对事务的管理
首先说下IOC,所谓的控制反转就是说应用所需要的依赖对象.不是由应用本身创建,而是由外部容器也就是spring的配置文件applicationContext.xml创建的.这种对对象创建控制权的转移就叫控制反转
这方面的例子网上很多.我就不列举了
依赖注入就是在运行期,有外部容器把需要的依赖对象注入到组件中
aop我理解的也不怎么清晰.下面是引用百度中的说明
AOP是OOP的延续,是Aspect Oriented Programming的缩写,意思是面向切面编程。可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,AOP可以说也是这种目标的一种实现。
上面说了那么多废话.本文的重点是spring提供的一个jdbc模板
先说下模板
直接贴代码了.我代码中只列举到了个别方法.想研究可以自己多看看
package com.smallq.dao.impl;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import com.smallq.dao.DaoException;
import com.smallq.dao.UserDao;
import com.smallq.domain.User;
public class UserDaoImpl implements UserDao {
private SimpleJdbcTemplate simpleJdbcTemplate;
/**
* 注入数据源
* @param dataSource
*/
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
/**
* 删除
*/
public void delete(int userId) {
try {
simpleJdbcTemplate.update("delete from user where id=?",
new Object[] { userId });
} catch (Exception e) {
throw new DaoException("删除用户出错" + e.getMessage(), e);
}
}
/**
* 根据id查找
*/
public User findUser(int userId) {
try {
return simpleJdbcTemplate.queryForObject(
"select * from user where id=?",
ParameterizedBeanPropertyRowMapper.newInstance(User.class),
new Object[] { userId });
} catch (Exception e) {
throw new DaoException("查询id为:" + userId + " 的用户出错"
+ e.getMessage(), e);
}
}
/**
* 查找所有
*/
@SuppressWarnings("unchecked")
public List<User> getUsers() {
try {
return simpleJdbcTemplate.getJdbcOperations().query(
"select * from user",
ParameterizedBeanPropertyRowMapper.newInstance(User.class));
} catch (Exception e) {
throw new DaoException("查询所有用户出错" + e.getMessage(), e);
}
}
/**
* 根据用户名密码查找
*/
public User login(String username, String password) {
try {
return simpleJdbcTemplate.queryForObject(
"select * from user where username=? and password=?",
ParameterizedBeanPropertyRowMapper.newInstance(User.class),
new Object[] { username, password });
} catch (Exception e) {
throw new DaoException("登陆出现异常" + e.getMessage(), e);
}
}
/**
* 添加
*/
public void save(User user) {
try{
simpleJdbcTemplate.update("insert into user values(?,?)",new Object[]{user.getUsername(),user.getPassword()});
}catch (Exception e) {
throw new DaoException("添加用户出现异常" + e.getMessage(), e);
}
// 下面这种方式比较安全.如果需要返回主键.推荐使用
// 主键是自动增长的.这里不需要指定主键
/*
String sql = "insert into user (username,password) values (:username,:password)";
SqlParameterSource param = new BeanPropertySqlParameterSource(user);
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
simpleJdbcTemplate.getNamedParameterJdbcOperations().update(sql,
param, keyHolder);
user.setId(keyHolder.getKey().intValue());
} catch (Exception e) {
throw new DaoException(e.getMessage(), e);
}
*/
// return user.getId(); 如果需要返回主键
}
/**
* 修改
*/
public void update(User user) {
try {
simpleJdbcTemplate.update(
"update user set username=?,password=? where id=?",
new Object[] { user.getUsername(), user.getPassword(),
user.getId() });
} catch (Exception e) {
throw new DaoException("执行更新出错" + e.getMessage(), e);
}
}
}
上面用到的DaoException 是一个继承RuntimeException的异常处理类
User是一个实体对象.我就不写代码了
spring配置文件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:context="http://www.springframework.org/schema/context" 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.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 启用注解自动装配 @Resource --> <context:annotation-config></context:annotation-config> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/smallq?userUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="5"/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 注解方式配置事务 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> <bean id="personDao" class="com.smallq.dao.impl.UserDaoImpl"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="personService" class="com.smallq.service.impl.UserServiceImpl"> </bean> </beans>
事务就先不说了.下篇说.附件见下篇