org.aspectj.lang.annotation.Before Java Examples

The following examples show how to use org.aspectj.lang.annotation.Before. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParamValidAspect.java    From runscore with Apache License 2.0 7 votes vote down vote up
@Before("paramValidAspect()")
public void before(JoinPoint joinPoint) {
	// 获取入参
	Object[] args = joinPoint.getArgs();
	for (Object arg : args) {
		if (arg == null) {
			throw new ParamValidException(BizError.参数异常.getCode(), "入参为空");
		}
		Set<ConstraintViolation<Object>> violations = validator.validate(arg);
		Iterator<ConstraintViolation<Object>> iterator = violations.iterator();
		// 参数校验不通过,直接抛出异常
		if (iterator.hasNext()) {
			ConstraintViolation<Object> violation = iterator.next();
			throw new ParamValidException(BizError.参数异常.getCode(),
					violation.getPropertyPath() + ":" + violation.getMessage());
		}
	}

}
 
Example #2
Source File: PreInsertAspect.java    From scaffold-cloud with MIT License 6 votes vote down vote up
@Before("   execution(* com.cms.scaffold.micro.*.dao.*.insert*(..)) " +
        "|| execution( * com.cms.scaffold.common.base.BaseMapper.insert*(..))")
public void insert(JoinPoint joinPoint){

    BaseEntity baseEntity = null;
    try {
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        if(obj!=null && obj.length > 0 && obj[0] instanceof BaseEntity){
            baseEntity = (BaseEntity)obj[0];
            if (baseEntity.getAddTime() == null){
                baseEntity.preInsert();
            }
        }
    }catch (Exception ex){
        logger.info(ex.getMessage(),ex);
    }

}
 
Example #3
Source File: ApiLogAspect.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * <方法执行前>
 *
 * @param point  [参数说明]
 * @param sysLog sysLog
 * @return void [返回类型说明]
 * @see [类、类#方法、类#成员]
 */
@Before(value = "log()")
public void before(JoinPoint point) throws Throwable {
    ApiLogger apiLogger = new ApiLogger();
    //将当前实体保存到threadLocal
    log.info("日志开始记录");
    logThreadLocal.set(apiLogger);
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();
    String operation = request.getMethod();
    apiLogger.setId(UuidUtil.getUuid());
    apiLogger.setCreateTime(LocalDateTime.now());
    if (!request.getRequestURI().contains(GlobalsConstants.LOGIN)) {
        apiLogger.setUserName(getUsername());
        apiLogger.setParams(Arrays.toString(point.getArgs()));
    }
    apiLogger.setMethodName(getMethodDescription(point) + ":" + point.getSignature().getName());
    apiLogger.setClassName(point.getTarget().getClass().getName());
    apiLogger.setMethod(operation);
    apiLogger.setUri(URLUtil.getPath(request.getRequestURI()));
    apiLogger.setIp(getIpAddr(request));
    apiLogger.setServiceId(getClientId());
    log.info("结束日志记录");
}
 
Example #4
Source File: HttpAspect.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@Before("pointcut()")
public void doVerifyBefore(JoinPoint joinPoint) {
	// 1. 登录校验
	MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
	String uri = request.getRequestURI();
       Long user_id = null;
	if (!uri.startsWith("/open") && !uri.equals("/")) {
		user_id = user.getUserId();
	}
	
	// 2. 开发环境-打印日志
	String ip = request.getRemoteHost();
       log.info("ip={}", ip);
	log.info("uri={}", uri);
	log.info("user_id={}", user_id);
	log.info("method={}", request.getMethod());
	log.info("class_method={}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName() + "()");
}
 
Example #5
Source File: ChatRecordAspect.java    From xechat with MIT License 6 votes vote down vote up
@Before("chatRecordPointcut()")
public void doBefore(JoinPoint joinPoint) {
    log.debug("before -> {}", joinPoint);

    MessageVO messageVO = null;
    Object[] args = joinPoint.getArgs();
    for (Object obj : args) {
        if (obj instanceof MessageVO) {
            messageVO = (MessageVO) obj;
            break;
        }
    }

    Assert.notNull(messageVO, "方法必需以MessageVO类或该类的子类作为参数");

    if (messageVO.getType() == MessageTypeEnum.USER) {
        // 对于User类型的消息做敏感词处理
        messageVO.setMessage(SensitiveWordUtils.loveChina(messageVO.getMessage()));
    }

    log.debug("添加聊天记录 -> {}", messageVO);
    chatRecordService.addRecord(ChatRecordDTO.toChatRecordDTO(messageVO));
}
 
Example #6
Source File: ActionAspect.java    From kvf-admin with MIT License 5 votes vote down vote up
@Before("logPointCut()")
public void before(JoinPoint joinPoint) {
	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	Method method = signature.getMethod();
	// 如果是退出登录请求。侧使用前置通知
	if ("logout".equals(method.getName())) {
		// 保存日志
		saveActionLog(joinPoint, 0, false);
	}
}
 
Example #7
Source File: AbstractAspectJAdvisorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked( Lockable mixin) {
	// Can also obtain the mixin (this) this way
	//Lockable mixin = (Lockable) jp.getThis();
	if (mixin.locked()) {
		throw new IllegalStateException();
	}
}
 
Example #8
Source File: GenericParameterMatchingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	counterAspect.reset();

	testBean = (GenericInterface<String>) ctx.getBean("testBean");
}
 
Example #9
Source File: DynamicDataSourceAspect.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 选择数据源 DataSource
 *
 * @param point the point
 */
@Before("daoAspect()")
public void switchDataSource(JoinPoint point) {
    if (openSaasProperties.getTenantId() != null) {
        DynamicDataSourceContextHolder.setDataSourceKey(openSaasProperties.getTenantId());
        logger.info("==> Switch DataSource to [{}] in Method [{}] tenant is [{}]", DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature(),openSaasProperties.getTenantId());
    }else{
        DynamicDataSourceContextHolder.setDataSourceKey("master");
    }
}
 
Example #10
Source File: SystemLogAspect.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
 *
 * @param joinPoint 切点
 * @throws InterruptedException
 */
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) throws InterruptedException {

    //线程绑定变量(该数据只有当前请求的线程可见)
    Date beginTime = new Date();
    beginTimeThreadLocal.set(beginTime);
}
 
Example #11
Source File: ServiceLogAspect.java    From MyCommunity with Apache License 2.0 5 votes vote down vote up
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
    // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes == null) {
        return;
    }
    HttpServletRequest request = attributes.getRequest();
    String ip = request.getRemoteHost();
    String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
}
 
Example #12
Source File: AdviceAspectConfig.java    From code with Apache License 2.0 5 votes vote down vote up
/******advice********/

    //@After("matchAnno()") //方法执行完成之后(不论是否有异常)
    //@After("matchException()") //方法执行完成之后(不论是否有异常)
    //@AfterThrowing("matchException()") //抛出异常之后执行
    //@AfterThrowing("matchAnno()") //不抛异常不执行
    //public void after(){
    //    System.out.println("###after");
    //}

    //@AfterReturning(value ="matchReturn()",returning = "result") // 获取方法的返回值
    //public void after(Object result){
    //    System.out.println("###after returning:"+result);
    //}

    //@Around("matchAnno()") //测试@Around正常情况
    //@Around("matchException()")// 测试@Around出现异常
    //public Object after(ProceedingJoinPoint pjp) {
    //    System.out.println("###before");
    //    Object result = null;
    //    try {
    //        result = pjp.proceed(pjp.getArgs());
    //        System.out.println("###after returning:" + result);
    //    } catch (Throwable e) {
    //        System.out.println("###catch ex");
    //        //throw
    //        e.printStackTrace();
    //    } finally {
    //        System.out.println("###finally");
    //    }
    //    return result;
    //}

    // 使用@Before校验参数
    @Before("matchLongArg() && args(productId)")
    public void before(Long productId){
        System.out.println("###before,get args:"+productId);
    }
 
Example #13
Source File: AbstractAspectJAdvisorFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked( Lockable mixin) {
	// Can also obtain the mixin (this) this way
	//Lockable mixin = (Lockable) jp.getThis();
	if (mixin.locked()) {
		throw new IllegalStateException();
	}
}
 
Example #14
Source File: ValidateTenantAspect.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Before("execution(* com.github.tangyi.auth.security.CustomUserDetailsServiceImpl.load*(..)) && args(tenantCode,..)")
public void validateTenantCode(String tenantCode) throws TenantNotFoundException {
	// 获取tenantCode
	if (StringUtils.isBlank(tenantCode))
		throw new TenantNotFoundException("tenantCode cant not be null");
	// 先获取租户信息
	ResponseBean<Tenant> tenantResponseBean = userServiceClient.findTenantByTenantCode(tenantCode);
	if (!ResponseUtil.isSuccess(tenantResponseBean))
		throw new ServiceException("get tenant info failed: " + tenantResponseBean.getMsg());
	Tenant tenant = tenantResponseBean.getData();
	if (tenant == null)
		throw new TenantNotFoundException("tenant does not exist");
}
 
Example #15
Source File: ModelValidator.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before(value = "@annotation(annotation) && args(companyId, customerID, custParameters)", argNames = "annotation,companyId,customerID,custParameters")
public void validate(Validate annotation, int companyId, int customerID, Map<?, ?> custParameters) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value());
   	}

       Validator validator = new Validator(resources, annotation.value());
       validator.setParameter(Validator.BEAN_PARAM, custParameters);
       validateInternal(validator);

}
 
Example #16
Source File: BeanNamePointcutAtAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	testBean1 = (ITestBean) ctx.getBean("testBean1");
	testBean3 = (ITestBean) ctx.getBean("testBean3");
}
 
Example #17
Source File: ModelValidator.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before(value = "@annotation(annotation) && args(companyId, modelId)")
public void validate(Validate annotation, int companyId, int modelId) throws ValidatorException {
	if(log.isDebugEnabled()) {
		log.debug("formName: " + annotation.value() + ", companyId: " + companyId);
	}

	Validator validator = new Validator(resources, annotation.value());
	validator.setParameter(Validator.BEAN_PARAM, companyId);
	validator.setParameter(Validator.BEAN_PARAM, modelId);

	validateInternal(validator);
}
 
Example #18
Source File: GenericBridgeMethodMatchingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (GenericCounterAspect) ctx.getBean("counterAspect");
	counterAspect.count = 0;

	testBean = (DerivedInterface<String>) ctx.getBean("testBean");
}
 
Example #19
Source File: ModelValidator.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before(value = "@annotation(annotation) && args(model, username, companyId, ..)")
public void validate(Validate annotation, Object model, String username, int companyId) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value()+", model:"+model.getClass().getName() + ", username: " + username);
   	}

   	validateInternal(annotation, model);
}
 
Example #20
Source File: GenericParameterMatchingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	counterAspect.reset();

	testBean = (GenericInterface<String>) ctx.getBean("testBean");
}
 
Example #21
Source File: AbstractAspectJAdvisorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)", argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(
		JoinPoint jp, MutableModifiable mixin, Object newValue) {

	/*
	 * We use the mixin to check and, if necessary, change,
	 * modification status. We need the JoinPoint to get the
	 * setter method. We use newValue for comparison.
	 * We try to invoke the getter if possible.
	 */

	if (mixin.isModified()) {
		// Already changed, don't need to change again
		//System.out.println("changed");
		return;
	}

	// Find the current raw value, by invoking the corresponding setter
	Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod());
	boolean modified = true;
	if (correspondingGetter != null) {
		try {
			Object oldValue = correspondingGetter.invoke(jp.getTarget());
			//System.out.println("Old value=" + oldValue + "; new=" + newValue);
			modified = !ObjectUtils.nullSafeEquals(oldValue, newValue);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			// Don't sweat on exceptions; assume value was modified
		}
	}
	else {
		//System.out.println("cannot get getter for " + jp);
	}
	if (modified) {
		mixin.markDirty();
	}
}
 
Example #22
Source File: ModelValidator.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before(value = "@annotation(annotation) && args(model, ..)")
   public void validate(Validate annotation, Object model) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value()+", model:"+model.getClass().getName());
   	}

   	validateInternal(annotation, model);
}
 
Example #23
Source File: ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
	testBean = (TestInterface) ctx.getBean("testBean");
	testAnnotatedClassBean = (TestInterface) ctx.getBean("testAnnotatedClassBean");
	testAnnotatedMethodBean = (TestInterface) ctx.getBean("testAnnotatedMethodBean");
	counter = (Counter) ctx.getBean("counter");
	counter.reset();
}
 
Example #24
Source File: LoggerAdvice.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@Before("within(com.hua..*) && @annotation(loggerManage)")
//切入点
public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
	logger.info("执行 " + loggerManage.description() + " 开始");
	logger.info(joinPoint.getSignature().toString());
	logger.info(parseParames(joinPoint.getArgs()));
}
 
Example #25
Source File: ConfigurationClassAspectIntegrationTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Before("execution(* org.springframework.tests.sample.beans.TestBean.absquatulate(..)) && target(testBean)")
public void touchBean(TestBean testBean) {
	testBean.setName("advisedName");
}
 
Example #26
Source File: PerTargetAspect.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Before("execution(void *.set*(int))")
public void countSetter() {
	++count;
}
 
Example #27
Source File: AbstractAspectJAdvisorFactoryTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Before("execution(* getAge())")
public void throwException() throws Exception {
	throw ex;
}
 
Example #28
Source File: TwoAdviceAspect.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Before("execution(* org.springframework.tests.sample.beans.ITestBean.setAge(int)) && args(newAge)")
public void countSet(int newAge) throws Exception {
	++totalCalls;
}
 
Example #29
Source File: UpdatePayAspect.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Before("updatePay()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    log.info("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤");
    check(joinPoint);
}
 
Example #30
Source File: AnnoAspectConfig.java    From code with Apache License 2.0 4 votes vote down vote up
@Before("matchAnno()")
public void before() {
    System.out.println("");
    System.out.println("##before method");
}