spring boot 中的面向切面编程 AOP

每天一篇博客之AOP记录

aop,可能很多人不理解,只知道是面向切面编程,函数式开发的一种方式衍生,其实我也不怎么懂,我只知道这个东西很方便,不用动以前的源码,就能切入一个程序,比方说我需要了解别人的浏览记录,浏览时间什么的,不用动以前的代码,也可以完成,不多BB,上代码

/**
 * Created by w on 2018/12/24.
 * 拦截查看商品详细的方法,添加浏览记录
 */
@Aspect
@Service
public class BrowseHistoryAop {
    @Autowired
    BrowseHistoryRepository browseHistoryRepository;//这个是一个查询仓库,小伙伴们需要用到自己的仓库层,应该都会

    @Pointcut("execution(* cn.qdefense.b2b.service.impl.ProductServiceImpl.showProductDetail(..))")//这个是精准定位在什么位置
    public void excudeService() {
    }

    @AfterReturning(returning = "rtr", pointcut = "excudeService()")
    @Transactional
    void addBrowseHistory(JoinPoint joinPoint, Object rtr) throws Throwable {
        JSONObject result = JSON.parseObject(JSON.toJSONString(rtr));//这个是接口返回结果值
        String customerId = SecurityUtil.getCurrentUserId();//这个是我自定义获取用户的id
        if (result.get("id") != null && result.get("companyId")!=null) {
            BrowseHistory browseHistory = new BrowseHistory();
            //企业id
            browseHistory.setProductId(String.valueOf(result.get("id")));
            //用户id
            browseHistory.setCustomerId(customerId);
            setBrowseHistory(browseHistory,result);
            //新增浏览历史记录
            browseHistoryRepository.save(browseHistory);
        }
    }
    void setBrowseHistory(BrowseHistory browseHistory,JSONObject result)
    {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();//aop中最快捷获取request的方法
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        String ip = request.getRemoteAddr();
        //浏览时间
        browseHistory.setBrowseDate(DateUtil.now());
        //企业ID
        browseHistory.setCompanyId(String.valueOf(result.get("companyId")));
        browseHistory.setIp(ip);
        browseHistory.setSessionId(session.getId());
    }
}

代码许多是我自己的东西,需要掌握的东西不多,注意的点是几个注解,,将注解弄好就OK了

猜你喜欢

转载自blog.csdn.net/wgxu123/article/details/87859827