设备物联的项目有个需求,需要在获取到设备信息后判断设备是否异常信息,想了一下决定用aop来是先,接收到设备信息需要将设备信息插入到数据库,因此,将切入点定义到插入的方法之上;
项目使用的架构是ssm架构,不做赘述
在spring-content.xml中增加如下配置
<aop:aspectj-autoproxy /> <!--强制使用cglib--> <aop:aspectj-autoproxy proxy-target-class="true"/>
编写自己的自定义注解:
** * * 自定义注解 拦截service 设备状态信息保存 * Created by lewKay on 2017/3/8. */ @Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WaringMessagePush { String description() default ""; }
编写切面类:
**s * Created by LewKay on 2017/3/7. * 切面类 * 切入到报警信息如果有预警就在此处插入到数据库 */ @Aspect @Service public class SendWaringMessageAop{ //将报警信息保存到数据库 @Autowired private WaringMessageService waringMessageService; //切入点 @Pointcut("@annotation(com.jctl.cloud.common.annotation.waring.WaringMessagePush)") public void waringMessagePushAspect(){ } /** * 前置通知 将报警信息保存到数据库 */ @Before("waringMessagePushAspect()") public void addWaringMessage(JoinPoint joinPoint){ try { System.out.println("********************************这里是前置通知:传递信息为"); } catch (Exception e) { e.printStackTrace(); } } }
在具体的service方法上加上自己的注解:
@Transactional(readOnly = false) @WaringMessagePush(description = "描述信息,测试用的") //自定义的注解 public void saveOrUpdate(ResultSet resultSet,String relayId) { List<String> clintMacs = resultSet.getGatewayResultSet().getClientMacList(); if (clintMacs == null) { return; } for (String clintMac : clintMacs) { Node temp = nodeDao.getByNodeMac(clintMac); if(temp==null){ Node newNode = new Node(clintMac,relayId,new Date()); save(newNode); } } }
测试一下:
2017-03-08 11:44:13,415 DEBUG [modules.sys.dao.LogDao.insert] - <== Updates: 1 2017-03-08 11:44:18,484 DEBUG [cloud.modules.sys.interceptor.LogInterceptor] - 开始计时: 11:44:18.484 URI: /manager/waring/waringCycle/form ********************************这里是前置通知:传递信息为 2017-03-08 11:44:18,489 DEBUG [manager.waring.dao.WaringCycleDao.get] - ==> Preparing: SELECT a.id AS "id", a.node_num AS "nodeNum", a.property AS "property", a.max AS "max", a.min AS "min", a.cycle AS "cycle", a.create_by AS "createBy.id", a.create_date AS "createDate", a.update_by AS "updateBy.id", a.update_date AS "updateDate" FROM jc_waring_cycle a WHERE a.id = ? 2017-03-08 11:44:18,489 DEBUG [manager.waring.dao.WaringCycleDao.get] - ==> Parameters: 2(String) 2017-03-08 11:44:18,491 DEBUG [manager.waring.dao.WaringCycleDao.get] - <== Total: 1
aop已经执行,下一步获取插入的参数,判断是否超出预警值这里就不做赘述了