whbing 2020-05-05
首先是保存实体类信息的entity层:
package edu.youzg.entity; public class UserInfo { private int id; private String name; private String password; private float balance; public UserInfo() { } public UserInfo(String name) { this.name = name; } public UserInfo(String name, String password) { this.password = password; this.name = name; } public UserInfo(int id, String name, int balance) { this.id = id; this.name = name; this.balance = balance; } public UserInfo(int id, String name, String password, int balance) { this.id = id; this.name = name; this.password = password; this.balance = balance; } public int getId() { return id; } public UserInfo setId(int id) { this.id = id; return this; } public String getName() { return name; } public UserInfo setName(String name) { this.name = name; return this; } public String getPassword() { return password; } public UserInfo setPassword(String password) { this.password = password; return this; } public float getBalance() { return balance; } public UserInfo setBalance(float balance) { this.balance = balance; return this; } @Override public String toString() { StringBuffer str = new StringBuffer(); str.append("账户[").append(name).append("]目前余额为:[").append(balance).append("]元"); return str.toString(); } }
接下来是联系数据库的dao层:
package edu.youzg.dao; import edu.youzg.entity.UserInfo; public interface IUserDao { void saveUser(String name, String password); void updateInfo(String name, String password, int id); void updateBalance(int id, float deltaMoney); UserInfo queryByLoginName(String name); UserInfo queryByID(int id); void deleteUser(String name, int id); }
package edu.youzg.dao; import edu.youzg.entity.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; /** * 用户的数据库访问类 */ @Repository public class UserDao implements IUserDao { @Autowired private JdbcTemplate jt; @Override public void saveUser(String name, String password) { String sql = "insert into account(name, password, balance) values(?, ?, ?)"; jt.update(sql, name, password, 0); } @Override public void updateInfo(String name, String password, int id) { String sql = "update account set name=?, password=? where id=?"; jt.update(sql, name, password, id); } @Override public void updateBalance(int id, float deltaMoney) { String sql = "update account set balance=balance+? where id=?"; jt.update(sql, deltaMoney, id); } @Override public UserInfo queryByLoginName(String name) { String sql = "select * from account where name=? "; List<UserInfo> list = jt.query(sql, new BeanPropertyRowMapper<UserInfo>(UserInfo.class), name); if (list!=null && list.size()>=1){ return list.get(0); } return null; } @Override public UserInfo queryByID(int id) { String sql="select * from account where id=?"; //返回一条数据 // return jt.queryForObject(sql,new BeanPropertyRowMapper<UserInfo>(UserInfo.class),name); List<UserInfo> list = jt.query(sql, new BeanPropertyRowMapper<UserInfo>(UserInfo.class), id); if(list!=null && list.size()>=1){ return list.get(0); } return null; } @Override public void deleteUser(String name, int id) { String sql = "delete from account where name=? and id=?"; jt.update(sql, name, id); } }
然后是提供对外功能的service层:
package edu.youzg.service; import edu.youzg.entity.UserInfo; /** * @Author: Youzg * @CreateTime: 2020-05-05 10:06 * @Description:带你深究Java的本质! */ public interface IUserService { // 用户功能 UserInfo register(UserInfo user); UserInfo login(UserInfo user); void saveMoney(UserInfo user, float money); boolean withdrawMonney(UserInfo user, float money); float queryBalance(UserInfo user); void transfer(UserInfo fromUser, UserInfo toUser, float money); // 管理员功能 void deleteUser(UserInfo user); }
package edu.youzg.service; import edu.youzg.dao.IUserDao; import edu.youzg.entity.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * 用户业务逻辑 */ @Transactional //添加 事务控制 @Service("userService") public class UserService implements IUserService { //数据库访问对象 @Autowired private IUserDao dao; @Override public UserInfo register(UserInfo user) { String name = user.getName(); String pass = user.getPassword(); UserInfo userInfo = dao.queryByLoginName(name); if (null!=userInfo) { System.out.println("用户名已存在!"); return new UserInfo().setId(-1); } dao.saveUser(name, pass); // 获取id,以便上层处理 UserInfo res = dao.queryByLoginName(name); return res; } @Override public UserInfo login(UserInfo user) { UserInfo userInfo = dao.queryByLoginName(user.getName()); if (userInfo.getId() > 0) { return userInfo; } return null; } @Override public void saveMoney(UserInfo user, float money) { UserInfo userInfo = dao.queryByLoginName(user.getName()); if (null==userInfo || userInfo.getId() <= 0) { return; } dao.updateBalance(userInfo.getId(), money); } @Override public boolean withdrawMonney(UserInfo user, float money) { UserInfo userInfo = dao.queryByLoginName(user.getName()); if (null == userInfo || userInfo.getBalance() < money) { return false; } dao.updateBalance(userInfo.getId(), -money); return true; } @Override public float queryBalance(UserInfo user) { UserInfo userInfo = dao.queryByLoginName(user.getName()); if (null == userInfo) { return -1; } return userInfo.getBalance(); } @Override public void deleteUser(UserInfo user) { UserInfo userInfo = dao.queryByLoginName(user.getName()); if (null == userInfo) { return; } dao.deleteUser(userInfo.getName(), userInfo.getId()); } // 转账业务逻辑 @Override public void transfer(UserInfo fromUser, UserInfo toUser, float money) { UserInfo from = dao.queryByLoginName(fromUser.getName()); UserInfo to = dao.queryByLoginName(toUser.getName()); if (null==from || null==to) { return; } //账号-钱 dao.updateBalance(from.getId(), -money); //账号+钱 dao.updateBalance(to.getId(), money); } }
接下来是运用了aop技术、用于日志管理的切面层:
package edu.youzg.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component @Aspect public class LoggerAspect { @Pointcut("execution(* edu.youzg.service.*.*(..))") public void pointCut(){} @Around("pointCut()") public Object around(ProceedingJoinPoint pjp) throws Throwable { Object result = null; long stime = System.currentTimeMillis(); try { result = pjp.proceed(pjp.getArgs());//执行目标业务逻辑 } finally { long etime = System.currentTimeMillis(); long time = etime - stime; //方法执行耗时时间 String mname = pjp.getSignature().getName(); String cname = pjp.getTarget().getClass().getName(); //输出什么类,什么方法,什么时间,什么参数被执行了 String msg = String.format("类名:" + cname + "方法名:" + mname + "执行耗时(毫秒):" + time); System.out.println(msg); } return result; } }
最后是用于配置spring、开启各种注解扫描的配置层:
package edu.youzg.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; /** * 使用java类配置spring */ @Configuration//声明这是spring配置类 @ComponentScan("edu.youzg")//扫描包 @EnableAspectJAutoProxy//开启aop注解支持 @PropertySource("youzgDB.properties")//读取配置文件 @EnableTransactionManagement//开启事务解析器 public class SpringConfig { @Value("${db.username}") private String userName; @Value("${db.password}") private String passWord; @Value("${db.url}") private String url; @Value("${db.driverClassName}") private String driverClassName; // 创建数据源 @Bean public DruidDataSource getDruidDataSource(){ DruidDataSource ds=new DruidDataSource(); ds.setUsername(userName); ds.setPassword(passWord); ds.setUrl(url); ds.setDriverClassName(driverClassName); //更多数据库连接池调优参数 根据官方文档设置即可 return ds; } //创建jdbc模板类对象 @Bean public JdbcTemplate getJdbcTemplate(DataSource ds){ return new JdbcTemplate(ds); } //创建事务管理器 @Bean public DataSourceTransactionManager getDataSourceTransactionManager(DataSource ds){ return new DataSourceTransactionManager(ds); } }
db.driverClassName=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/dbstudy?serverTimezone=UTC&characterEncoding=utf-8 db.username=root db.password=123456
最后,本人来给出测试类:
package edu.youzg.test; import edu.youzg.config.SpringConfig; import edu.youzg.dao.TransferDao; import edu.youzg.entity.UserInfo; import edu.youzg.service.IUserService; import edu.youzg.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @Author: Youzg * @CreateTime: 2020-05-03 08:50 * @Description:带你深究Java的本质! */ public class YouzgTest { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); IUserService service = context.getBean("userService", IUserService.class); UserInfo newUser = new UserInfo("youzg666", "123456"); service.register(newUser); service.saveMoney(newUser, 100); service.transfer(newUser, new UserInfo("youzg"), 20); } }
接下来,本人来展示下运行结果: