org.springframework.aop.framework.AopProxyUtils Java Examples

The following examples show how to use org.springframework.aop.framework.AopProxyUtils. 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: DcsSchedulingConfiguration.java    From schedule-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
    if (this.nonAnnotatedClasses.contains(targetClass)) return bean;
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods == null) return bean;
    for (Method method : methods) {
        DcsScheduled dcsScheduled = AnnotationUtils.findAnnotation(method, DcsScheduled.class);
        if (null == dcsScheduled || 0 == method.getDeclaredAnnotations().length) continue;
        List<ExecOrder> execOrderList = Constants.execOrderMap.computeIfAbsent(beanName, k -> new ArrayList<>());
        ExecOrder execOrder = new ExecOrder();
        execOrder.setBean(bean);
        execOrder.setBeanName(beanName);
        execOrder.setMethodName(method.getName());
        execOrder.setDesc(dcsScheduled.desc());
        execOrder.setCron(dcsScheduled.cron());
        execOrder.setAutoStartup(dcsScheduled.autoStartup());
        execOrderList.add(execOrder);
        this.nonAnnotatedClasses.add(targetClass);
    }
    return bean;
}
 
Example #2
Source File: RocketMQTemplate.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
private Type getMessageType(RocketMQLocalRequestCallback rocketMQLocalRequestCallback) {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(rocketMQLocalRequestCallback);
    Type matchedGenericInterface = null;
    while (Objects.nonNull(targetClass)) {
        Type[] interfaces = targetClass.getGenericInterfaces();
        if (Objects.nonNull(interfaces)) {
            for (Type type : interfaces) {
                if (type instanceof ParameterizedType && (Objects.equals(((ParameterizedType) type).getRawType(), RocketMQLocalRequestCallback.class))) {
                    matchedGenericInterface = type;
                    break;
                }
            }
        }
        targetClass = targetClass.getSuperclass();
    }
    if (Objects.isNull(matchedGenericInterface)) {
        return Object.class;
    }

    Type[] actualTypeArguments = ((ParameterizedType) matchedGenericInterface).getActualTypeArguments();
    if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
        return actualTypeArguments[0];
    }
    return Object.class;
}
 
Example #3
Source File: RocketMQTransactionConfiguration.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
private void registerTransactionListener(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (!RocketMQLocalTransactionListener.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " is not instance of " + RocketMQLocalTransactionListener.class.getName());
    }
    RocketMQTransactionListener annotation = clazz.getAnnotation(RocketMQTransactionListener.class);
    RocketMQTemplate rocketMQTemplate = (RocketMQTemplate) applicationContext.getBean(annotation.rocketMQTemplateBeanName());
    if (((TransactionMQProducer) rocketMQTemplate.getProducer()).getTransactionListener() != null) {
        throw new IllegalStateException(annotation.rocketMQTemplateBeanName() + " already exists RocketMQLocalTransactionListener");
    }
    ((TransactionMQProducer) rocketMQTemplate.getProducer()).setExecutorService(new ThreadPoolExecutor(annotation.corePoolSize(), annotation.maximumPoolSize(),
        annotation.keepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(annotation.blockingQueueSize())));
    ((TransactionMQProducer) rocketMQTemplate.getProducer()).setTransactionListener(RocketMQUtil.convert((RocketMQLocalTransactionListener) bean));
    log.debug("RocketMQLocalTransactionListener {} register to {} success", clazz.getName(), annotation.rocketMQTemplateBeanName());
}
 
Example #4
Source File: ExtProducerResetConfiguration.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
private void registerTemplate(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (!RocketMQTemplate.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " is not instance of " + RocketMQTemplate.class.getName());
    }

    ExtRocketMQTemplateConfiguration annotation = clazz.getAnnotation(ExtRocketMQTemplateConfiguration.class);
    GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext;
    validate(annotation, genericApplicationContext);

    DefaultMQProducer mqProducer = createProducer(annotation);
    // Set instanceName same as the beanName
    mqProducer.setInstanceName(beanName);
    try {
        mqProducer.start();
    } catch (MQClientException e) {
        throw new BeanDefinitionValidationException(String.format("Failed to startup MQProducer for RocketMQTemplate {}",
            beanName), e);
    }
    RocketMQTemplate rocketMQTemplate = (RocketMQTemplate) bean;
    rocketMQTemplate.setProducer(mqProducer);
    rocketMQTemplate.setMessageConverter(rocketMQMessageConverter.getMessageConverter());
    log.info("Set real producer to :{} {}", beanName, annotation.value());
}
 
Example #5
Source File: DefaultRocketMQListenerContainer.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
private MethodParameter getMethodParameter() {
    Class<?> targetClass;
    if (rocketMQListener != null) {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQListener);
    } else {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQReplyListener);
    }
    Type messageType = this.getMessageType();
    Class clazz = null;
    if (messageType instanceof ParameterizedType && messageConverter instanceof SmartMessageConverter) {
        clazz = (Class) ((ParameterizedType) messageType).getRawType();
    } else if (messageType instanceof Class) {
        clazz = (Class) messageType;
    } else {
        throw new RuntimeException("parameterType:" + messageType + " of onMessage method is not supported");
    }
    try {
        final Method method = targetClass.getMethod("onMessage", clazz);
        return new MethodParameter(method, 0);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        throw new RuntimeException("parameterType:" + messageType + " of onMessage method is not supported");
    }
}
 
Example #6
Source File: CachingAnnotationsAspect.java    From jim-framework with Apache License 2.0 6 votes vote down vote up
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// The method may be on an interface, but we need attributes from the
	// target class. If the target class is null, the method will be
	// unchanged.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example #7
Source File: TaskManager.java    From Taroco-Scheduler with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 封装ScheduledMethodRunnable对象
 */
private ScheduledMethodRunnable buildScheduledRunnable(Object bean, String targetMethod, String params, String extKeySuffix, String scheduleKey) {
    Method method;
    Class<?> clazz;
    if (AopUtils.isAopProxy(bean)) {
        clazz = AopProxyUtils.ultimateTargetClass(bean);
    } else {
        clazz = bean.getClass();
    }
    if (params != null) {
        method = ReflectionUtils.findMethod(clazz, targetMethod, String.class);
    } else {
        method = ReflectionUtils.findMethod(clazz, targetMethod);
    }
    if (ObjectUtils.isEmpty(method)) {
        zkClient.getTaskGenerator().getScheduleTask().saveRunningInfo(scheduleKey, ScheduleServer.getInstance().getUuid(), "method not found");
        log.error("启动动态任务失败: {}, 失败原因: {}", scheduleKey, "method not found");
        return null;
    }
    return new ScheduledMethodRunnable(bean, method, params, extKeySuffix);
}
 
Example #8
Source File: BeanValidationPostProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Perform validation of the given bean.
 * @param bean the bean instance to validate
 * @see javax.validation.Validator#validate
 */
protected void doValidate(Object bean) {
	Assert.state(this.validator != null, "No Validator set");
	Object objectToValidate = AopProxyUtils.getSingletonTarget(bean);
	if (objectToValidate == null) {
		objectToValidate = bean;
	}
	Set<ConstraintViolation<Object>> result = this.validator.validate(objectToValidate);

	if (!result.isEmpty()) {
		StringBuilder sb = new StringBuilder("Bean state is invalid: ");
		for (Iterator<ConstraintViolation<Object>> it = result.iterator(); it.hasNext();) {
			ConstraintViolation<Object> violation = it.next();
			sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
			if (it.hasNext()) {
				sb.append("; ");
			}
		}
		throw new BeanInitializationException(sb.toString());
	}
}
 
Example #9
Source File: RaftAnnotationBeanPostProcessor.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
private void processRaftService(Object bean, String beanName) {

        final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);

        RaftService raftServiceAnnotation = beanClass.getAnnotation(RaftService.class);

        if (raftServiceAnnotation == null) {
            return;
        }

        Class<?> interfaceType = raftServiceAnnotation.interfaceType();

        if (interfaceType.equals(void.class)) {
            Class<?>[] interfaces = beanClass.getInterfaces();

            if (interfaces == null || interfaces.length == 0 || interfaces.length > 1) {
                throw new RuntimeException(
                    "Bean " + beanName
                            + " does not has any interface or has more than one interface.");
            }

            interfaceType = interfaces[0];
        }
        String serviceUniqueId = getServiceId(interfaceType, raftServiceAnnotation.uniqueId());
        Processor.getInstance().addWorker(serviceUniqueId, interfaceType, bean);
    }
 
Example #10
Source File: DynamicTaskManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
private static ScheduledMethodRunnable _buildScheduledRunnable(Object bean, String targetMethod, String params) throws Exception {

		Assert.notNull(bean, "target object must not be null");
		Assert.hasLength(targetMethod, "Method name must not be empty");

		Method method;
		ScheduledMethodRunnable scheduledMethodRunnable;

		Class<?> clazz;
		if (AopUtils.isAopProxy(bean)) {
			clazz = AopProxyUtils.ultimateTargetClass(bean);
		} else {
			clazz = bean.getClass();
		}
		if (params != null) {
			method = ReflectionUtils.findMethod(clazz, targetMethod, String.class);
		} else {
			method = ReflectionUtils.findMethod(clazz, targetMethod);
		}

		Assert.notNull(method, "can not find method named " + targetMethod);
		scheduledMethodRunnable = new ScheduledMethodRunnable(bean, method, params);
		return scheduledMethodRunnable;
	}
 
Example #11
Source File: SpringNettyConfiguration.java    From spring-boot-netty with MIT License 6 votes vote down vote up
private Map<String, List<ChannelHandler>> buildFilterHandlers(final Map<String, Object> filters) {
    final Map<String, List<ChannelHandler>> filterHandlers = new HashMap<>();
    filters.forEach((ignored, bean) -> {
        final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);
        if (!ChannelHandler.class.isAssignableFrom(beanClass)) {
            throw new IllegalStateException("Bean annotated with @NettyFilter doesn't implement ChannelHandler: " + bean);
        }

        final NettyFilter annotation = findAnnotation(beanClass, NettyFilter.class);
        if (annotation != null) {
            final String serverName = annotation.serverName();
            filterHandlers.computeIfAbsent(serverName, k -> new ArrayList<>())
                    .add((ChannelHandler) bean);
        }
    });

    //noinspection NestedMethodCall
    filterHandlers.values().forEach(l -> l.sort(FILTER_BEAN_COMPARATOR));

    return filterHandlers;
}
 
Example #12
Source File: CachingAnnotationsAspect.java    From spring-cache-self-refresh with MIT License 6 votes vote down vote up
/**
 * Finds out the most specific method when the execution reference is an
 * interface or a method with generic parameters
 * 
 * @param pjp
 * @return
 */
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// The method may be on an interface, but we need attributes from the
	// target class. If the target class is null, the method will be
	// unchanged.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example #13
Source File: BeanValidationPostProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Perform validation of the given bean.
 * @param bean the bean instance to validate
 * @see javax.validation.Validator#validate
 */
protected void doValidate(Object bean) {
	Assert.state(this.validator != null, "No Validator set");
	Object objectToValidate = AopProxyUtils.getSingletonTarget(bean);
	if (objectToValidate == null) {
		objectToValidate = bean;
	}
	Set<ConstraintViolation<Object>> result = this.validator.validate(objectToValidate);

	if (!result.isEmpty()) {
		StringBuilder sb = new StringBuilder("Bean state is invalid: ");
		for (Iterator<ConstraintViolation<Object>> it = result.iterator(); it.hasNext();) {
			ConstraintViolation<Object> violation = it.next();
			sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
			if (it.hasNext()) {
				sb.append("; ");
			}
		}
		throw new BeanInitializationException(sb.toString());
	}
}
 
Example #14
Source File: ScheduledAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
	if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler ||
			bean instanceof ScheduledExecutorService) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}

	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
	if (!this.nonAnnotatedClasses.contains(targetClass) &&
			AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
		Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
				(MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
					Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
							method, Scheduled.class, Schedules.class);
					return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
				});
		if (annotatedMethods.isEmpty()) {
			this.nonAnnotatedClasses.add(targetClass);
			if (logger.isTraceEnabled()) {
				logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
			}
		}
		else {
			// Non-empty set of methods
			annotatedMethods.forEach((method, scheduledMethods) ->
					scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
			if (logger.isTraceEnabled()) {
				logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName +
						"': " + annotatedMethods);
			}
		}
	}
	return bean;
}
 
Example #15
Source File: SynchronizingAspect.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Around("synchronizePointcut()")
public Object synchronizeInvocation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = methodSignature.getMethod();
    Object target = proceedingJoinPoint.getTarget();
    Object[] args = proceedingJoinPoint.getArgs();
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    Synchronized annotation = getAnnotation(targetClass, method);
    Validate.notNull(annotation, "Could not find @Synchronized annotation!");

    Lock lock = getLock(targetClass, method, args, annotation);
    if (lock == null) {
        logger.debug("No lock obtained for call [{}] on targetClass [{}] - proceeding without synchronization on " +
                "thread {}", new Object[]{method.getName(), targetClass.getName(), Thread.currentThread().getId()});
        return proceedingJoinPoint.proceed();
    } else {
        try {
            logger.debug("Lock obtained for call [{}] on targetClass [{}] - proceeding with synchronization on thread {}",
                    new Object[]{method.getName(), targetClass.getName(), Thread.currentThread().getId()});
            lock.lock();
            return proceedingJoinPoint.proceed();
        } finally {
            lock.unlock();
            lockService.returnLock(lock);
        }
    }
}
 
Example #16
Source File: LimiterAspectSupport.java    From Limiter with Apache License 2.0 5 votes vote down vote up
/**
 * @param invocation
 * @param target
 * @param method
 * @param args
 * @return
 * @throws Throwable
 */
protected Object execute(final MethodInvocation invocation, Object target, Method method, Object[] args) throws Throwable {

    if (this.initialized) {
        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
        LimitedResourceSource limitedResourceSource = getLimitedResourceSource();
        if (limitedResourceSource != null) {
            Collection<LimitedResource> limitedResources = limitedResourceSource.getLimitedResource(targetClass, method);
            if (!CollectionUtils.isEmpty(limitedResources)) {
                Collection<LimiterExecutionContext> contexts = getLimiterOperationContexts(limitedResources, method, args, target, targetClass);
                LimitContextsValueWrapper limitContextsValueWrapper = limitContexts(contexts);
                if (limitContextsValueWrapper.value()) {
                    try {
                        return invocation.proceed();
                    } catch (Throwable e) {
                        throw e;
                    } finally {
                        releaseContexts(contexts);
                    }
                } else {
                    return limitContextsValueWrapper.getLimiterFailResolveResult();
                }

            }
        }
    }
    return invocation.proceed();
}
 
Example #17
Source File: SimpleTaskAutoConfigurationTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Test
public void testRepository() {
	ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner()
			.withConfiguration(
					AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class,
							SimpleTaskAutoConfiguration.class,
							SingleTaskConfiguration.class));
	applicationContextRunner.run((context) -> {

		TaskRepository taskRepository = context.getBean(TaskRepository.class);
		assertThat(taskRepository).isNotNull();
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(taskRepository);
		assertThat(targetClass).isEqualTo(SimpleTaskRepository.class);
	});
}
 
Example #18
Source File: AopUtil.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
/**
 * @param target
 * @return
 */
public static Class<?> getTargetClass(Object target) {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    if (targetClass == null && target != null) {
        targetClass = target.getClass();
    }
    return targetClass;
}
 
Example #19
Source File: AbstractApplicationEventMulticaster.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
	synchronized (this.retrievalMutex) {
		// Explicitly remove target for a proxy, if registered already,
		// in order to avoid double invocations of the same listener.
		Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
		if (singletonTarget instanceof ApplicationListener) {
			this.defaultRetriever.applicationListeners.remove(singletonTarget);
		}
		this.defaultRetriever.applicationListeners.add(listener);
		this.retrieverCache.clear();
	}
}
 
Example #20
Source File: CacheAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Class<?> getTargetClass(Object target) {
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
	if (targetClass == null && target != null) {
		targetClass = target.getClass();
	}
	return targetClass;
}
 
Example #21
Source File: JCacheAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
	// Check whether aspect is enabled to cope with cases where the AJ is pulled in automatically
	if (this.initialized) {
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
		JCacheOperation<?> operation = getCacheOperationSource().getCacheOperation(method, targetClass);
		if (operation != null) {
			CacheOperationInvocationContext<?> context =
					createCacheOperationInvocationContext(target, args, operation);
			return execute(context, invoker);
		}
	}

	return invoker.invoke();
}
 
Example #22
Source File: SpringNettyConfiguration.java    From spring-boot-netty with MIT License 5 votes vote down vote up
private void fillControllerHandlers(final Map<String, List<Method>> connectHandlers,
                                    final Map<String, List<Method>> disconnectHandlers,
                                    final Map<String, List<Method>> messageHandlers) {

    final Map<String, Object> controllers = beanFactory.getBeansWithAnnotation(NettyController.class);
    controllers.forEach((ignored, bean) -> {
        final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);
        final Method[] methods = ReflectionUtils.getAllDeclaredMethods(beanClass);

        for (final Method method : methods) {
            final boolean isConnectHandler = checkForConnectHandler(connectHandlers, method);
            final boolean isDisconnectHandler = checkForDisconnectHandler(disconnectHandlers, method);
            final boolean isMessageHandler = checkForMessageHandler(messageHandlers, method);

            final boolean isHandler = isConnectHandler || isDisconnectHandler || isMessageHandler;
            if (isHandler) {
                final long c = Stream.of(isConnectHandler, isDisconnectHandler, isMessageHandler)
                        .filter(b -> b)
                        .count();

                if (c != 1) {
                    throw new IllegalStateException("Method " + method +
                            " is handler of various events. Currently this is not allowed!");
                }
            }
        }
    });

    //noinspection NestedMethodCall
    connectHandlers.values().forEach(l -> l.sort(ON_CONNECT_METHOD_COMPARATOR));

    //noinspection NestedMethodCall
    disconnectHandlers.values().forEach(l -> l.sort(ON_DISCONNECT_METHOD_COMPARATOR));

    //noinspection NestedMethodCall
    messageHandlers.values().forEach(l -> l.sort(ON_MESSAGE_METHOD_COMPARATOR));
}
 
Example #23
Source File: CacheAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Class<?> getTargetClass(Object target) {
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
	if (targetClass == null && target != null) {
		targetClass = target.getClass();
	}
	return targetClass;
}
 
Example #24
Source File: AbstractCacheAnnotationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public void testRootVars(CacheableService<?> service) {
	Object key = new Object();
	Object r1 = service.rootVars(key);
	assertSame(r1, service.rootVars(key));
	Cache cache = cm.getCache("testCache");
	// assert the method name is used
	String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
	assertNotNull(cache.get(expectedKey));
}
 
Example #25
Source File: SpringNettyConfiguration.java    From spring-boot-netty with MIT License 5 votes vote down vote up
private List<Supplier<ChannelHandler>> buildFilterSuppliers(final BiMap<String, Object> filterBeans,
                                                    final Map<String, List<ChannelHandler>> filterHandlers,
                                                    final String name) {

    return filterHandlers.getOrDefault(name, new ArrayList<>())
            .stream()
            .map(o -> {
                final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(o);
                final ChannelHandler.Sharable sharable = findAnnotation(beanClass, ChannelHandler.Sharable.class);
                if (sharable == null) {
                    final Scope scope = findAnnotation(beanClass, Scope.class);

                    //noinspection NestedMethodCall
                    if ((scope == null) || !ConfigurableBeanFactory.SCOPE_PROTOTYPE.equals(scope.value())) {
                        throw new IllegalStateException("Non-sharable handler should be presented by a prototype bean");
                    }
                }

                final String beanName = filterBeans.inverse().get(o);

                @SuppressWarnings("UnnecessaryLocalVariable")
                final Supplier<ChannelHandler> beanSupplier = (sharable == null)?
                        () -> (ChannelHandler) beanFactory.getBean(beanName, beanClass) :
                        () -> o;

                return beanSupplier;
            }).collect(Collectors.toList());
}
 
Example #26
Source File: JCacheAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Class<?> getTargetClass(Object target) {
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
	if (targetClass == null && target != null) {
		targetClass = target.getClass();
	}
	return targetClass;
}
 
Example #27
Source File: MethodJmsListenerEndpoint.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public Method getMostSpecificMethod() {
	if (this.mostSpecificMethod != null) {
		return this.mostSpecificMethod;
	}
	else if (AopUtils.isAopProxy(this.bean)) {
		Class<?> target = AopProxyUtils.ultimateTargetClass(this.bean);
		return AopUtils.getMostSpecificMethod(getMethod(), target);
	}
	else {
		return getMethod();
	}
}
 
Example #28
Source File: DefaultRocketMQListenerContainer.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
private Type getMessageType() {
    Class<?> targetClass;
    if (rocketMQListener != null) {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQListener);
    } else {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQReplyListener);
    }
    Type matchedGenericInterface = null;
    while (Objects.nonNull(targetClass)) {
        Type[] interfaces = targetClass.getGenericInterfaces();
        if (Objects.nonNull(interfaces)) {
            for (Type type : interfaces) {
                if (type instanceof ParameterizedType &&
                    (Objects.equals(((ParameterizedType) type).getRawType(), RocketMQListener.class) || Objects.equals(((ParameterizedType) type).getRawType(), RocketMQReplyListener.class))) {
                    matchedGenericInterface = type;
                    break;
                }
            }
        }
        targetClass = targetClass.getSuperclass();
    }
    if (Objects.isNull(matchedGenericInterface)) {
        return Object.class;
    }

    Type[] actualTypeArguments = ((ParameterizedType) matchedGenericInterface).getActualTypeArguments();
    if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
        return actualTypeArguments[0];
    }
    return Object.class;
}
 
Example #29
Source File: JmsListenerAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	if (bean instanceof AopInfrastructureBean || bean instanceof JmsListenerContainerFactory ||
			bean instanceof JmsListenerEndpointRegistry) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}

	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
	if (!this.nonAnnotatedClasses.contains(targetClass) &&
			AnnotationUtils.isCandidateClass(targetClass, JmsListener.class)) {
		Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
				(MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> {
					Set<JmsListener> listenerMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
							method, JmsListener.class, JmsListeners.class);
					return (!listenerMethods.isEmpty() ? listenerMethods : null);
				});
		if (annotatedMethods.isEmpty()) {
			this.nonAnnotatedClasses.add(targetClass);
			if (logger.isTraceEnabled()) {
				logger.trace("No @JmsListener annotations found on bean type: " + targetClass);
			}
		}
		else {
			// Non-empty set of methods
			annotatedMethods.forEach((method, listeners) ->
					listeners.forEach(listener -> processJmsListener(listener, method, bean)));
			if (logger.isDebugEnabled()) {
				logger.debug(annotatedMethods.size() + " @JmsListener methods processed on bean '" + beanName +
						"': " + annotatedMethods);
			}
		}
	}
	return bean;
}
 
Example #30
Source File: MethodJmsListenerEndpoint.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
public Method getMostSpecificMethod() {
	if (this.mostSpecificMethod != null) {
		return this.mostSpecificMethod;
	}
	Method method = getMethod();
	if (method != null) {
		Object bean = getBean();
		if (AopUtils.isAopProxy(bean)) {
			Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
			method = AopUtils.getMostSpecificMethod(method, targetClass);
		}
	}
	return method;
}