Java Code Examples for org.springframework.aop.support.AopUtils#getTargetClass()

The following examples show how to use org.springframework.aop.support.AopUtils#getTargetClass() . 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: MonitoringSpringInterceptor.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private static String getClassPart(MethodInvocation invocation) {
	// si guice et pas Spring, alors remplacer AopUtils.getTargetClass() par getMethod().getDeclaringClass()
	// http://ninomartinez.wordpress.com/2010/05/14/guice-caching-interceptors/
	// (faire exemple avec un interceptor static)
	final Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());
	final MonitoredWithSpring classAnnotation = targetClass
			.getAnnotation(MonitoredWithSpring.class);
	if (classAnnotation == null || classAnnotation.name() == null
			|| classAnnotation.name().isEmpty()) {
		final Class<?> declaringClass = invocation.getMethod().getDeclaringClass();
		final MonitoredWithSpring declaringClassAnnotation = declaringClass
				.getAnnotation(MonitoredWithSpring.class);
		if (declaringClassAnnotation == null || declaringClassAnnotation.name() == null
				|| declaringClassAnnotation.name().isEmpty()) {
			return targetClass.getSimpleName();
		}
		return declaringClassAnnotation.name();
	}
	return classAnnotation.name();
}
 
Example 2
Source File: ApiBootDataSourceSwitchAnnotationInterceptor.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        // get class declared DataSourceSwitch annotation
        DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class);
        if (dataSourceSwitch == null) {
            // get declared DataSourceSwitch annotation
            dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class);
        }
        if (dataSourceSwitch != null) {
            // setting current thread use data source pool name
            DataSourceContextHolder.set(dataSourceSwitch.value());
        }
        return invocation.proceed();
    } finally {
        // remove current thread use datasource pool name
        DataSourceContextHolder.remove();
    }

}
 
Example 3
Source File: ApiBootDataSourceSwitchAnnotationInterceptor.java    From api-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Object methodResult;
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        // get class declared DataSourceSwitch annotation
        DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class);
        if (dataSourceSwitch == null) {
            // get declared DataSourceSwitch annotation
            dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class);
        }
        if (dataSourceSwitch != null) {
            // setting current thread use data source pool name
            DataSourceContextHolder.set(dataSourceSwitch.value());
        }
        methodResult = invocation.proceed();
    } finally {
        // remove current thread use datasource pool name
        DataSourceContextHolder.remove();
    }
    return methodResult;

}
 
Example 4
Source File: AnnotationBean.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private boolean isMatchPackage(Object bean) {
    if (annotationPackages == null || annotationPackages.length == 0) {
        return true;
    }
    Class clazz = bean.getClass();
    if(isProxyBean(bean)){
        clazz = AopUtils.getTargetClass(bean);
    }
    String beanClassName = clazz.getName();
    for (String pkg : annotationPackages) {
        if (beanClassName.startsWith(pkg)) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: MBeanExporter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Build an adapted MBean for the given bean instance, if possible.
 * <p>The default implementation builds a JMX 1.2 StandardMBean
 * for the target's MBean/MXBean interface in case of an AOP proxy,
 * delegating the interface's management operations to the proxy.
 * @param bean the original bean instance
 * @return the adapted MBean, or {@code null} if not possible
 */
@SuppressWarnings("unchecked")
protected DynamicMBean adaptMBeanIfPossible(Object bean) throws JMException {
	Class<?> targetClass = AopUtils.getTargetClass(bean);
	if (targetClass != bean.getClass()) {
		Class<?> ifc = JmxUtils.getMXBeanInterface(targetClass);
		if (ifc != null) {
			if (!ifc.isInstance(bean)) {
				throw new NotCompliantMBeanException("Managed bean [" + bean +
						"] has a target class with an MXBean interface but does not expose it in the proxy");
			}
			return new StandardMBean(bean, ((Class<Object>) ifc), true);
		}
		else {
			ifc = JmxUtils.getMBeanInterface(targetClass);
			if (ifc != null) {
				if (!ifc.isInstance(bean)) {
					throw new NotCompliantMBeanException("Managed bean [" + bean +
							"] has a target class with an MBean interface but does not expose it in the proxy");
				}
				return new StandardMBean(bean, ((Class<Object>) ifc));
			}
		}
	}
	return null;
}
 
Example 6
Source File: MetadataNamingStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reads the {@code ObjectName} from the source-level metadata associated
 * with the managed resource's {@code Class}.
 */
@Override
public ObjectName getObjectName(Object managedBean, String beanKey) throws MalformedObjectNameException {
	Class<?> managedClass = AopUtils.getTargetClass(managedBean);
	ManagedResource mr = this.attributeSource.getManagedResource(managedClass);

	// Check that an object name has been specified.
	if (mr != null && StringUtils.hasText(mr.getObjectName())) {
		return ObjectNameManager.getInstance(mr.getObjectName());
	}
	else {
		try {
			return ObjectNameManager.getInstance(beanKey);
		}
		catch (MalformedObjectNameException ex) {
			String domain = this.defaultDomain;
			if (domain == null) {
				domain = ClassUtils.getPackageName(managedClass);
			}
			Hashtable<String, String> properties = new Hashtable<String, String>();
			properties.put("type", ClassUtils.getShortName(managedClass));
			properties.put("name", beanKey);
			return ObjectNameManager.getInstance(domain, properties);
		}
	}
}
 
Example 7
Source File: MethodNameFluentValidatorPostProcessor.java    From fluent-validator with Apache License 2.0 5 votes vote down vote up
@Override
public FluentValidator postProcessBeforeDoValidate(FluentValidator fluentValidator, MethodInvocation
        methodInvocation) {
    Preconditions.checkNotNull(methodInvocation, "MethodInvocation should not be NULL");
    String methodName = methodInvocation.getMethod().getName();
    Class<?> targetClass = AopUtils.getTargetClass(methodInvocation.getThis());
    fluentValidator.putAttribute2Context(KEY_METHOD_NAME, methodName);
    fluentValidator.putAttribute2Context(KEY_TARGET_CLASS_SIMPLE_NAME, targetClass);
    return fluentValidator;
}
 
Example 8
Source File: CompensableMethodInterceptor.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private CompensableInvocation getCompensableInvocation(String identifier, Method method, Object[] args,
		Compensable annotation, Object target) {
	CompensableInvocationImpl invocation = new CompensableInvocationImpl();
	invocation.setArgs(args);

	invocation.setIdentifier(identifier);
	invocation.setSimplified(annotation.simplified());

	invocation.setMethod(method); // class-method

	Class<?> currentClazz = AopUtils.getTargetClass(target);

	Method[] methodArray = currentClazz.getDeclaredMethods();
	boolean confirmFlag = false;
	boolean cancelFlag = false;

	for (int i = 0; (confirmFlag == false || cancelFlag == false) && i < methodArray.length; i++) {
		Method element = methodArray[i];
		if (element.getAnnotation(CompensableConfirm.class) != null) {
			confirmFlag = true;
			invocation.setConfirmableKey(identifier);
		}
		if (element.getAnnotation(CompensableCancel.class) != null) {
			cancelFlag = true;
			invocation.setCancellableKey(identifier);
		}
	}

	return invocation;
}
 
Example 9
Source File: ServiceBean.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
protected Class getServiceClass(T ref) {
    if (AopUtils.isAopProxy(ref)) {
        return AopUtils.getTargetClass(ref);
    }
    return super.getServiceClass(ref);
}
 
Example 10
Source File: SpringUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static Class<?> getTargetClass(Object candidate) {
	Class<?> targetClass = AopUtils.getTargetClass(candidate);
	if(ClassUtils.isCglibProxyClass(targetClass)){
		targetClass = candidate.getClass().getSuperclass();
	}
	return targetClass;
}
 
Example 11
Source File: MetadataNamingStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Reads the {@code ObjectName} from the source-level metadata associated
 * with the managed resource's {@code Class}.
 */
@Override
public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException {
	Assert.state(this.attributeSource != null, "No JmxAttributeSource set");
	Class<?> managedClass = AopUtils.getTargetClass(managedBean);
	ManagedResource mr = this.attributeSource.getManagedResource(managedClass);

	// Check that an object name has been specified.
	if (mr != null && StringUtils.hasText(mr.getObjectName())) {
		return ObjectNameManager.getInstance(mr.getObjectName());
	}
	else {
		Assert.state(beanKey != null, "No ManagedResource attribute and no bean key specified");
		try {
			return ObjectNameManager.getInstance(beanKey);
		}
		catch (MalformedObjectNameException ex) {
			String domain = this.defaultDomain;
			if (domain == null) {
				domain = ClassUtils.getPackageName(managedClass);
			}
			Hashtable<String, String> properties = new Hashtable<>();
			properties.put("type", ClassUtils.getShortName(managedClass));
			properties.put("name", beanKey);
			return ObjectNameManager.getInstance(domain, properties);
		}
	}
}
 
Example 12
Source File: ClassUtils.java    From DataGenerator with Apache License 2.0 5 votes vote down vote up
public static Class<?> getTargetClass(Object obj) {
    if (AopUtils.isAopProxy(obj)) {
        return AopUtils.getTargetClass(obj);
    } else {
        return (obj instanceof Class) ? (Class) obj : obj.getClass();
    }
}
 
Example 13
Source File: AnnotationProviderRegister.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
    if(bean instanceof AnnotationBusinessProviderBuilder) {
        return true;
    }
    
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    for(Method m : targetClass.getMethods()) {
        for(Annotation a : m.getAnnotations()) {
            AnnotationBusinessProviderBuilder builder = mapHandler.get(a.annotationType());
            if(builder != null) {
                
                Class<?>[] parameterTypes = m.getParameterTypes();
                if(parameterTypes.length != 1) {
                    throw new IllegalArgumentException("method should conatins only One parameter, method:" + m);
                }
                
                @SuppressWarnings("unchecked")
                Class<? extends EasyTransRequest<?, ?>> requestClass = (Class<? extends EasyTransRequest<?, ?>>) parameterTypes[0];
                
              //create and register in bean factory
                BusinessProvider<?> provider = builder.create(a, bean, m, requestClass,beanName);
                
                Class<? extends EasyTransRequest<?, ?>> cfgClass = builder.getActualConfigClass(a, requestClass);
                BusinessIdentifer businessIdentifer = ReflectUtil.getBusinessIdentifer(cfgClass);
                
                if(businessIdentifer == null) {
                    throw new RuntimeException("can not find BusinessIdentifer in request class!" + requestClass);
                }
                
                beanFactory.registerSingleton(businessIdentifer.appId() + "-" + businessIdentifer.busCode() +"-provider", provider);
            }
        }
    }
    return true;
}
 
Example 14
Source File: MessageQueueConsumerBeanPostProcessor.java    From synapse with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) {
    if (!this.nonAnnotatedClasses.contains(bean.getClass())) {
        final Class<?> targetClass = AopUtils.getTargetClass(bean);
        final Map<Method, Set<MessageQueueConsumer>> annotatedMethods = findMethodsAnnotatedWithMessageQueueConsumer(targetClass);
        if (annotatedMethods.isEmpty()) {
            this.nonAnnotatedClasses.add(bean.getClass());
            LOG.trace("No @MessageQueueConsumer annotations found on bean type: {}", bean.getClass());
        } else {
            registerMessageQueueConsumers(bean, beanName, annotatedMethods);
        }
    }
    return bean;
}
 
Example 15
Source File: ShardingTransactionTypeInterceptor.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private ShardingTransactionType getAnnotation(final MethodInvocation invocation) {
    Objects.requireNonNull(invocation.getThis());
    Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());
    ShardingTransactionType result = getMethodAnnotation(invocation, targetClass);
    return null != result ? result : targetClass.getAnnotation(ShardingTransactionType.class);
}
 
Example 16
Source File: SpringStopwatchSource.java    From javasimon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** Get target class. */
protected final Class<?> getTargetClass(MethodInvocation methodInvocation) {
	return AopUtils.getTargetClass(methodInvocation.getThis());
}
 
Example 17
Source File: TransactionalAnnotationTest.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public void getNonAnnotatedTransactionalServices() {
    /* We only want to run getNonAnnotatedTransactionalSerivces once.
     * The tests actually just read the Maps that are generated here.
     */
    if (incorrectlyAnnotatedTransactionalServices != null) {
        return;
    }
    incorrectlyAnnotatedTransactionalServices = new HashMap<String, Class<? extends Object>>();
    nonAnnotatedTransactionalServices = new HashMap<String, String>();
    doubleAnnotatedTransactionalServices = new HashMap<String, String>();

    String[] beanNames = SpringContext.getBeanNames();
    for (String beanName : beanNames) {
        if ( beanName.endsWith( "-parentBean" ) ) {
            continue;
        }
        Object bean = null;
        try {
            bean = SpringContext.getBean(beanName);
        } catch ( BeanIsAbstractException ex ) {
            // do nothing, ignore
        } catch (Exception e) {
            LOG.warn("Caught exception while trying to obtain service: " + beanName);
            LOG.warn(e.getClass().getName() + " : " + e.getMessage(), e );
        }
        if (bean != null) {
            Class<? extends Object> beanClass = bean.getClass();
            if (beanClass.getName().matches(".*\\$Proxy.*")) {
                beanClass = AopUtils.getTargetClass(bean);
            }
            if (beanClass.getName().startsWith("org.kuali")
                    && !Modifier.isAbstract(beanClass.getModifiers())
                    && !beanClass.getName().endsWith("DaoOjb")
                    && !beanClass.getName().endsWith("DaoJdbc")
                    && !beanClass.getName().endsWith("Factory")
                    && !beanClass.getName().contains("Lookupable")
                    && !isClassAnnotated(beanName, beanClass)) {
                incorrectlyAnnotatedTransactionalServices.put(beanName, beanClass);
            }
        }
    }
    return;
}
 
Example 18
Source File: AbstractTraceInterceptor.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Determine the class to use for logging purposes.
 * @param target the target object to introspect
 * @return the target class for the given object
 * @see #setHideProxyClassNames
 */
protected Class<?> getClassForLogging(Object target) {
	return (this.hideProxyClassNames ? AopUtils.getTargetClass(target) : target.getClass());
}
 
Example 19
Source File: AbstractTraceInterceptor.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Determine the class to use for logging purposes.
 * @param target the target object to introspect
 * @return the target class for the given object
 * @see #setHideProxyClassNames
 */
protected Class<?> getClassForLogging(Object target) {
	return (this.hideProxyClassNames ? AopUtils.getTargetClass(target) : target.getClass());
}
 
Example 20
Source File: DubboComponentScanRegistrarTest.java    From dubbo-2.6.5 with Apache License 2.0 2 votes vote down vote up
@Test
public void test() {

    AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext();

    providerContext.register(ProviderConfiguration.class);

    providerContext.refresh();

    DemoService demoService = providerContext.getBean(DemoService.class);

    String value = demoService.sayName("Mercy");

    Assert.assertEquals("Hello,Mercy", value);

    Class<?> beanClass = AopUtils.getTargetClass(demoService);

    // DemoServiceImpl with @Transactional
    Assert.assertEquals(DemoServiceImpl.class, beanClass);

    // Test @Transactional is present or not
    Assert.assertNotNull(findAnnotation(beanClass, Transactional.class));

    AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext();

    consumerContext.register(ConsumerConfiguration.class);

    consumerContext.refresh();

    ConsumerConfiguration consumerConfiguration = consumerContext.getBean(ConsumerConfiguration.class);

    demoService = consumerConfiguration.getDemoService();

    value = demoService.sayName("Mercy");

    Assert.assertEquals("Hello,Mercy", value);

    ConsumerConfiguration.Child child = consumerContext.getBean(ConsumerConfiguration.Child.class);

    // From Child

    demoService = child.getDemoServiceFromChild();

    Assert.assertNotNull(demoService);

    value = demoService.sayName("Mercy");

    Assert.assertEquals("Hello,Mercy", value);

    // From Parent

    demoService = child.getDemoServiceFromParent();

    Assert.assertNotNull(demoService);

    value = demoService.sayName("Mercy");

    Assert.assertEquals("Hello,Mercy", value);

    // From Ancestor

    demoService = child.getDemoServiceFromAncestor();

    Assert.assertNotNull(demoService);

    value = demoService.sayName("Mercy");

    Assert.assertEquals("Hello,Mercy", value);

    providerContext.close();
    consumerContext.close();


}