/**
* 文件在系统中的存储基本路径
* @return
*/
public static String getImgBasePath() {
String os = System.getProperty("os.name");
String basePath="";
if(os.toLowerCase().startsWith("win")) {
basePath="D:/project/o2o/image/";
}else {
basePath="/Users111/lifuqing/project/image/";
}
basePath = basePath.replace("/", seperator);
return basePath;
}
如上段代码显示,我们讲Users故意写成Users111
则下段代码从生产水印开始,开始包异常.
/**
* 处理缩略图,并生成新的生成图片的相对路径值
* @param thumbnail
* @param targetAddr
* @return
*/
public static String generateThunbnail(File thumbnail,String targetAddr) {
//年月日时分秒+五位随机数 的字符串作为文件名字
String realFileName = getRandomFileName();
//获取文件的后缀
String extension = getFileExtension(thumbnail);
//创建目录
makeDirPath(targetAddr);
//文件地址的拼接
String relativeAddr = targetAddr+realFileName+extension;
logger.debug("current relativeAddr is :"+relativeAddr);
//生成一个新的文件
File dest=new File(PathUtil.getImgBasePath()+relativeAddr);
logger.debug("current complete addr is :"+PathUtil.getImgBasePath()+relativeAddr);
//生产水印
try {
Thumbnails.of(thumbnail)
.size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath+"/watermark.jpg")), 0.25f)
.outputQuality(0.8)
.toFile(dest);
}catch(RuntimeException e) {
logger.error(e.toString());
e.printStackTrace();
}catch(Exception e) {
logger.error(e.toString());
e.printStackTrace();
}
//返回添加水印的相对地址
return relativeAddr;
}
上段代码会被com.imooc.o2o.service.impl.ShopServiceImpl.addShopImg.这段代码调用,详情如下:
private void addShopImg(Shop shop, File shopImg) {
// 货物shop图片目录的相对值路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
String shopImgAddr = ImageUtil.generateThunbnail(shopImg, dest);
shop.setShopAddr(shopImgAddr);
}
下面这段代码com.imooc.o2o.service.impl.ShopServiceImpl.ShopExecution.要求数据库具有回滚功能,但是他调用了上段代码com.imooc.o2o.service.impl.ShopServiceImpl.addShopImg.,
出现了异常;
想问一下老师,这种情况如果addShop方法内调用的其它方法出现了异常,系统没有回滚,如何解决.
@Transactional//事物
public ShopExecution addShop(Shop shop, File shopImg) {
//空值判断
if(shop == null) {
return new ShopExecution(ShopStateEnum.NULL_SHOP);
}
try {
//给店铺信息赋初始值
shop.setEnableStatus(0);
shop.setCreateTime(new Date());
shop.setLastEditTime(new Date());
//添加店铺信息
int effectedNum =shopDao.insertShop(shop);
//检查是商铺信息否插入成功
if(effectedNum <=0) {
//这种方式抛出异常,事物才会回滚
throw new ShopOperationException("店铺创建失败");
}else {
if(shopImg !=null) {
try {
//图片与商铺信息合并
addShopImg(shop,shopImg);
}catch(Exception e) {
throw new ShopOperationException("addShopImg error ");
}
//更新店铺的图片地址
effectedNum =shopDao.updateShop(shop);
if(effectedNum <=0) {
throw new ShopOperationException("更新图片失败");
}
}
}
}catch(Exception e) {
throw new ShopOperationException("addShop error:"+e.getMessage());
}
return new ShopExecution(ShopStateEnum.CHECK,shop);
}
登录后可查看更多问答,登录/注册
SSM商铺V1.0,解决毕设痛点;SpringBoot商铺V2.0,满足工作刚需
了解课程