org.springframework.util.ClassUtils Java Examples

The following examples show how to use org.springframework.util.ClassUtils. 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: StartupApplicationListener.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> sources(ApplicationReadyEvent event) {
	Method method = ReflectionUtils.findMethod(SpringApplication.class, "getAllSources");
	if (method == null) {
		method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
	}
	ReflectionUtils.makeAccessible(method);
	@SuppressWarnings("unchecked")
	Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method, event.getSpringApplication());
	Set<Class<?>> result = new LinkedHashSet<>();
	for (Object object : objects) {
		if (object instanceof String) {
			object = ClassUtils.resolveClassName((String) object, null);
		}
		result.add((Class<?>) object);
	}
	return result;
}
 
Example #2
Source File: AnnotationDrivenBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
	ManagedList<Object> result = new ManagedList<Object>();
	for (Object object : list) {
		if (object instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
			String className = beanDef.getBeanDefinition().getBeanClassName();
			Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
			if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
				RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
				adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
				result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
				continue;
			}
		}
		result.add(object);
	}
	return result;
}
 
Example #3
Source File: ConstructorArgumentValues.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Look for the next generic argument value that matches the given type,
 * ignoring argument values that have already been used in the current
 * resolution process.
 * @param requiredType the type to match (can be {@code null} to find
 * an arbitrary next generic argument value)
 * @param requiredName the name to match (can be {@code null} to not
 * match argument values by name, or empty String to match any name)
 * @param usedValueHolders a Set of ValueHolder objects that have already been used
 * in the current resolution process and should therefore not be returned again
 * @return the ValueHolder for the argument, or {@code null} if none found
 */
@Nullable
public ValueHolder getGenericArgumentValue(@Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) {
	for (ValueHolder valueHolder : this.genericArgumentValues) {
		if (usedValueHolders != null && usedValueHolders.contains(valueHolder)) {
			continue;
		}
		if (valueHolder.getName() != null && !"".equals(requiredName) &&
				(requiredName == null || !valueHolder.getName().equals(requiredName))) {
			continue;
		}
		if (valueHolder.getType() != null &&
				(requiredType == null || !ClassUtils.matchesTypeName(requiredType, valueHolder.getType()))) {
			continue;
		}
		if (requiredType != null && valueHolder.getType() == null && valueHolder.getName() == null &&
				!ClassUtils.isAssignableValue(requiredType, valueHolder.getValue())) {
			continue;
		}
		return valueHolder;
	}
	return null;
}
 
Example #4
Source File: MockServerContainerContextCustomizerFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public ContextCustomizer createContextCustomizer(Class<?> testClass,
		List<ContextConfigurationAttributes> configAttributes) {

	if (webSocketPresent && isAnnotatedWithWebAppConfiguration(testClass)) {
		try {
			Class<?> clazz = ClassUtils.forName(MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME,
					getClass().getClassLoader());
			return (ContextCustomizer) BeanUtils.instantiateClass(clazz);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable WebSocket test support; could not load class: " +
					MOCK_SERVER_CONTAINER_CONTEXT_CUSTOMIZER_CLASS_NAME, ex);
		}
	}

	// Else, nothing to customize
	return null;
}
 
Example #5
Source File: ExtendedEntityManagerCreator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Actually create the EntityManager proxy.
 * @param rawEm raw EntityManager
 * @param emIfc the (potentially vendor-specific) EntityManager
 * interface to proxy, or {@code null} for default detection of all interfaces
 * @param cl the ClassLoader to use for proxy creation (maybe {@code null})
 * @param exceptionTranslator the PersistenceException translator to use
 * @param jta whether to create a JTA-aware EntityManager
 * (or {@code null} if not known in advance)
 * @param containerManaged whether to follow container-managed EntityManager
 * or application-managed EntityManager semantics
 * @param synchronizedWithTransaction whether to automatically join ongoing
 * transactions (according to the JPA 2.1 SynchronizationType rules)
 * @return the EntityManager proxy
 */
private static EntityManager createProxy(
		EntityManager rawEm, @Nullable Class<? extends EntityManager> emIfc, @Nullable ClassLoader cl,
		@Nullable PersistenceExceptionTranslator exceptionTranslator, @Nullable Boolean jta,
		boolean containerManaged, boolean synchronizedWithTransaction) {

	Assert.notNull(rawEm, "EntityManager must not be null");
	Set<Class<?>> ifcs = new LinkedHashSet<>();
	if (emIfc != null) {
		ifcs.add(emIfc);
	}
	else {
		ifcs.addAll(ClassUtils.getAllInterfacesForClassAsSet(rawEm.getClass(), cl));
	}
	ifcs.add(EntityManagerProxy.class);
	return (EntityManager) Proxy.newProxyInstance(
			(cl != null ? cl : ExtendedEntityManagerCreator.class.getClassLoader()),
			ClassUtils.toClassArray(ifcs),
			new ExtendedEntityManagerInvocationHandler(
					rawEm, exceptionTranslator, jta, containerManaged, synchronizedWithTransaction));
}
 
Example #6
Source File: CacheKeyGenerator.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Object generate(Object target, Method method, Object... params) {
    StringBuilder key = new StringBuilder();
    key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");

    if (params.length == 0) {
        key.append(NO_PARAM_KEY).toString();
    }

    for (Object param : params) {
        if (param == null) {
            key.append(NULL_PARAM_KEY);
        } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {
            key.append(param);
        } else if (param instanceof CacheKey) {
            key.append(((CacheKey) param).getCacheKey());
        } else {
            logger.warn("Using object " + param + " as cache key. Either use key='..' or implement CacheKey. Method is " + target.getClass() + "#" + method.getName());
            key.append(param.hashCode());
        }
    }

    return  key.toString();
}
 
Example #7
Source File: ProxyExchange.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public ServletInputStream getInputStream() throws IOException {
	Object body = body();
	MethodParameter output = new MethodParameter(
			ClassUtils.getMethod(BodySender.class, "body"), -1);
	ServletOutputToInputConverter response = new ServletOutputToInputConverter(
			this.response);
	ServletWebRequest webRequest = new ServletWebRequest(this.request, response);
	try {
		delegate.handleReturnValue(body, output, mavContainer, webRequest);
	}
	catch (HttpMessageNotWritableException
			| HttpMediaTypeNotAcceptableException e) {
		throw new IllegalStateException("Cannot convert body", e);
	}
	return response.getInputStream();
}
 
Example #8
Source File: NameMatchTransactionAttributeSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
	if (!ClassUtils.isUserLevelMethod(method)) {
		return null;
	}

	// Look for direct name match.
	String methodName = method.getName();
	TransactionAttribute attr = this.nameMap.get(methodName);

	if (attr == null) {
		// Look for most specific name match.
		String bestNameMatch = null;
		for (String mappedName : this.nameMap.keySet()) {
			if (isMatch(methodName, mappedName) &&
					(bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) {
				attr = this.nameMap.get(mappedName);
				bestNameMatch = mappedName;
			}
		}
	}

	return attr;
}
 
Example #9
Source File: SecurityAspect.java    From mcspring-boot with MIT License 6 votes vote down vote up
@Order(1)
@Before("within(@(@dev.alangomes.springspigot.security.Audit *) *) " +
        "|| execution(@(@dev.alangomes.springspigot.security.Audit *) * *(..)) " +
        "|| @within(dev.alangomes.springspigot.security.Audit)" +
        "|| execution(@dev.alangomes.springspigot.security.Audit * *(..))")
public void auditCall(JoinPoint joinPoint) {
    val sender = context.getSender();
    val method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    val signature = ClassUtils.getUserClass(method.getDeclaringClass()).getName() + "." + method.getName();
    val arguments = Arrays.stream(joinPoint.getArgs()).map(String::valueOf).collect(Collectors.joining(", "));

    AopAnnotationUtils.getAppliableAnnotations(method, Audit.class).stream()
            .filter(audit -> sender != null || !audit.senderOnly())
            .limit(1)
            .forEach(audit -> {
                if (sender != null) {
                    log.info(String.format("Player %s invoked %s(%s)", sender.getName(), signature, arguments));
                } else {
                    log.info(String.format("Server invoked %s(%s)", signature, arguments));
                }
            });
}
 
Example #10
Source File: ContextFunctionCatalogAutoConfigurationTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Test
public void componentScanJarFunction() {
	try {
		create("greeter.jar", ComponentScanJarConfiguration.class);
		assertThat(this.context.getBean("greeter")).isInstanceOf(Function.class);
		assertThat((Function<?, ?>) this.catalog.lookup(Function.class, "greeter"))
				.isInstanceOf(Function.class);
		assertThat(this.inspector
				.getInputType(this.catalog.lookup(Function.class, "greeter")))
						.isAssignableFrom(String.class);
		assertThat(this.inspector
				.getInputWrapper(this.catalog.lookup(Function.class, "greeter")))
						.isAssignableFrom(String.class);
	}
	finally {
		ClassUtils.overrideThreadContextClassLoader(getClass().getClassLoader());
	}
}
 
Example #11
Source File: LoggingEnvironmentApplicationListener.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
/**
 * deducing groupId, artifactId
 *
 * @param event
 */
private void onApplicationStartingEvent(ApplicationStartingEvent event) {
    if (ClassUtils.isPresent("ch.qos.logback.core.Appender",
            event.getSpringApplication().getClassLoader())) {
        // base package
        Class<?> mainClass = event.getSpringApplication().getMainApplicationClass();
        if (mainClass != null) {
            String basePackage = mainClass.getPackage().getName();
            System.setProperty("BASE_PACKAGE", basePackage);
        } else {
            System.setProperty("BASE_PACKAGE", "");
            logger.warn("can not set BASE_PACKAGE correctly");
        }

        // set logging system impl
        System.setProperty(LoggingSystem.SYSTEM_PROPERTY, FormulaLogbackSystem.class.getName());
    }
}
 
Example #12
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
	markBeanAsCreated(beanName);
	BeanDefinition mbd = getMergedBeanDefinition(beanName);
	RootBeanDefinition bd = null;
	if (mbd instanceof RootBeanDefinition) {
		RootBeanDefinition rbd = (RootBeanDefinition) mbd;
		bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
	}
	if (bd == null) {
		bd = new RootBeanDefinition(mbd);
	}
	if (!bd.isPrototype()) {
		bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
	}
	BeanWrapper bw = new BeanWrapperImpl(existingBean);
	initBeanWrapper(bw);
	populateBean(beanName, bd, bw);
	return initializeBean(beanName, existingBean, bd);
}
 
Example #13
Source File: ClassPathResource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation returns a description that includes the class path location.
 */
@Override
public String getDescription() {
	StringBuilder builder = new StringBuilder("class path resource [");
	String pathToUse = this.path;
	if (this.clazz != null && !pathToUse.startsWith("/")) {
		builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
		builder.append('/');
	}
	if (pathToUse.startsWith("/")) {
		pathToUse = pathToUse.substring(1);
	}
	builder.append(pathToUse);
	builder.append(']');
	return builder.toString();
}
 
Example #14
Source File: MessageMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
	Class<?> paramType = parameter.getParameterType();
	if (!paramType.isAssignableFrom(message.getClass())) {
			throw new MethodArgumentTypeMismatchException(message, parameter,
					"The actual message type [" + ClassUtils.getQualifiedName(message.getClass()) + "] " +
					"does not match the expected type [" + ClassUtils.getQualifiedName(paramType) + "]");
	}

	Class<?> expectedPayloadType = getPayloadType(parameter);
	Object payload = message.getPayload();
	if (payload != null && expectedPayloadType != null && !expectedPayloadType.isInstance(payload)) {
		throw new MethodArgumentTypeMismatchException(message, parameter,
				"The expected Message<?> payload type [" + ClassUtils.getQualifiedName(expectedPayloadType) +
				"] does not match the actual payload type [" + ClassUtils.getQualifiedName(payload.getClass()) + "]");
	}

	return message;
}
 
Example #15
Source File: CosmosConfigurationSupport.java    From spring-data-cosmosdb with MIT License 6 votes vote down vote up
protected Set<Class<?>> scanForEntities(String basePackage) throws ClassNotFoundException {
    if (!StringUtils.hasText(basePackage)) {
        return Collections.emptySet();
    }

    final Set<Class<?>> initialEntitySet = new HashSet<>();

    if (StringUtils.hasText(basePackage)) {
        final ClassPathScanningCandidateComponentProvider componentProvider =
                new ClassPathScanningCandidateComponentProvider(false);

        componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class));

        for (final BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) {
            final String className = candidate.getBeanClassName();
            Assert.notNull(className, "Bean class name is null.");

            initialEntitySet
                    .add(ClassUtils.forName(className, CosmosConfigurationSupport.class.getClassLoader()));
        }
    }

    return initialEntitySet;
}
 
Example #16
Source File: RpcExporterRegister.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                    BeanDefinitionRegistry registry) {
    Map<Class, String> serviceExporterMap = new HashMap<>();
    AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
    Collection<BeanDefinition> candidates = getCandidates(resourceLoader);
    for (BeanDefinition candidate : candidates) {
        Class<?> clazz = getClass(candidate.getBeanClassName());
        Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(clazz);
        if (interfaces.length != 1) {
            throw new BeanInitializationException("bean interface num must equal 1, " + clazz.getName());
        }
        String serviceBeanName = beanNameGenerator.generateBeanName(candidate, registry);
        String old = serviceExporterMap.putIfAbsent(interfaces[0], serviceBeanName);
        if (old != null) {
            throw new RuntimeException("interface already be exported by bean name:" + old);
        }
        registry.registerBeanDefinition(serviceBeanName, candidate);
    }
}
 
Example #17
Source File: SmartMessageMethodArgumentResolver.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
private Object convertPayload(Message<?> message, MethodParameter parameter,
		Class<?> targetPayloadType) {
	Object result = null;
	if (this.messageConverter instanceof SmartMessageConverter) {
		SmartMessageConverter smartConverter = (SmartMessageConverter) this.messageConverter;
		result = smartConverter.fromMessage(message, targetPayloadType, parameter);
	}
	else if (this.messageConverter != null) {
		result = this.messageConverter.fromMessage(message, targetPayloadType);
	}

	if (result == null) {
		throw new MessageConversionException(message,
				"No converter found from actual payload type '"
						+ ClassUtils.getDescriptiveType(message.getPayload())
						+ "' to expected payload type '"
						+ ClassUtils.getQualifiedName(targetPayloadType) + "'");
	}
	return result;
}
 
Example #18
Source File: XmlBeanFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * @since 3.2.8 and 4.0.2
 * @see <a href="https://jira.spring.io/browse/SPR-10785">SPR-10785</a> and <a
 *      href="https://jira.spring.io/browse/SPR-11420">SPR-11420</a>
 */
@Test
public void methodInjectedBeanMustBeOfSameEnhancedCglibSubclassTypeAcrossBeanFactories() {
	Class<?> firstClass = null;

	for (int i = 0; i < 10; i++) {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		new XmlBeanDefinitionReader(bf).loadBeanDefinitions(OVERRIDES_CONTEXT);

		final Class<?> currentClass = bf.getBean("overrideOneMethod").getClass();
		assertTrue("Method injected bean class [" + currentClass + "] must be a CGLIB enhanced subclass.",
			ClassUtils.isCglibProxyClass(currentClass));

		if (firstClass == null) {
			firstClass = currentClass;
		}
		else {
			assertEquals(firstClass, currentClass);
		}
	}
}
 
Example #19
Source File: VaadinConnectController.java    From flow with Apache License 2.0 5 votes vote down vote up
void validateEndpointBean(EndpointNameChecker endpointNameChecker,
        String name, Object endpointBean) {
    // Check the bean type instead of the implementation type in
    // case of e.g. proxies
    Class<?> beanType = ClassUtils.getUserClass(endpointBean.getClass());

    String endpointName = Optional
            .ofNullable(beanType.getAnnotation(Endpoint.class))
            .map(Endpoint::value).filter(value -> !value.isEmpty())
            .orElse(beanType.getSimpleName());
    if (endpointName.isEmpty()) {
        throw new IllegalStateException(String.format(
                "A bean with name '%s' and type '%s' is annotated with '%s' "
                        + "annotation but is an anonymous class hence has no name. ",
                name, beanType, Endpoint.class)
                + String.format(
                        "Either modify the bean declaration so that it is not an "
                                + "anonymous class or specify an endpoint " +
                                "name in the '%s' annotation",
                        Endpoint.class));
    }
    String validationError = endpointNameChecker.check(endpointName);
    if (validationError != null) {
        throw new IllegalStateException(
                String.format("Endpoint name '%s' is invalid, reason: '%s'",
                        endpointName, validationError));
    }

    vaadinEndpoints.put(endpointName.toLowerCase(Locale.ENGLISH),
            new VaadinEndpointData(endpointBean, beanType.getMethods()));
}
 
Example #20
Source File: RateLimiterAopAdvisor.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public RateLimiterAopAdvisor(RateLimiterManager rateLimiterManager) {
    setAdvice((MethodBeforeAdvice) (method, args, target) -> {
        String[] names = nameDiscoverer.getParameterNames(method);
        RateLimiter limiter = Optional.ofNullable(AnnotationUtils.findAnnotation(method, RateLimiter.class))
                .orElseGet(() -> AnnotationUtils.findAnnotation(ClassUtils.getUserClass(target), RateLimiter.class));
        if (limiter != null) {
            List<String> keyExpressionList = new ArrayList<>(Arrays.asList(limiter.key()));
            if (keyExpressionList.isEmpty()) {
                keyExpressionList.add(method.toString());
            }
            for (String keyExpress : keyExpressionList) {
                if (keyExpress.contains("${")) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("user", Authentication.current().map(Authentication::getUser).orElse(null));
                    for (int i = 0; i < args.length; i++) {
                        params.put(names.length > i ? names[i] : "arg" + i, args[i]);
                        params.put("arg" + i, args[i]);

                    }
                    keyExpress = ExpressionUtils.analytical(keyExpress, params, "spel");
                }
                log.debug("do rate limiter:[{}]. ", keyExpress);
                boolean success = rateLimiterManager
                        .getRateLimiter(keyExpress, limiter.permits(), limiter.timeUnit())
                        .tryAcquire(limiter.acquire(), limiter.acquireTimeUnit());
                if (!success) {
                    throw new TimeoutException("请求超时");
                }
            }
        }
    });
}
 
Example #21
Source File: ClassEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.hasText(text)) {
		setValue(ClassUtils.resolveClassName(text.trim(), this.classLoader));
	}
	else {
		setValue(null);
	}
}
 
Example #22
Source File: AnnotationConfigContextLoaderUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Detect the default configuration classes for the supplied test class.
 * <p>The returned class array will contain all static nested classes of
 * the supplied class that meet the requirements for {@code @Configuration}
 * class implementations as specified in the documentation for
 * {@link Configuration @Configuration}.
 * <p>The implementation of this method adheres to the contract defined in the
 * {@link org.springframework.test.context.SmartContextLoader SmartContextLoader}
 * SPI. Specifically, this method uses introspection to detect default
 * configuration classes that comply with the constraints required of
 * {@code @Configuration} class implementations. If a potential candidate
 * configuration class does not meet these requirements, this method will log a
 * debug message, and the potential candidate class will be ignored.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @return an array of default configuration classes, potentially empty but
 * never {@code null}
 */
public static Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) {
	Assert.notNull(declaringClass, "Declaring class must not be null");

	List<Class<?>> configClasses = new ArrayList<>();

	for (Class<?> candidate : declaringClass.getDeclaredClasses()) {
		if (isDefaultConfigurationClassCandidate(candidate)) {
			configClasses.add(candidate);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug(String.format(
					"Ignoring class [%s]; it must be static, non-private, non-final, and annotated " +
							"with @Configuration to be considered a default configuration class.",
					candidate.getName()));
			}
		}
	}

	if (configClasses.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Could not detect default configuration classes for test class [%s]: " +
					"%s does not declare any static, non-private, non-final, nested classes " +
					"annotated with @Configuration.", declaringClass.getName(), declaringClass.getSimpleName()));
		}
	}

	return ClassUtils.toClassArray(configClasses);
}
 
Example #23
Source File: ConfigurationClassPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
	if (bean instanceof ImportAware) {
		ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
		AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
		if (importingClass != null) {
			((ImportAware) bean).setImportMetadata(importingClass);
		}
	}
	return bean;
}
 
Example #24
Source File: AbstractAutowireCapableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void autowireBean(Object existingBean) {
	// Use non-singleton bean definition, to avoid registering bean as dependent bean.
	RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
	bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
	bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
	BeanWrapper bw = new BeanWrapperImpl(existingBean);
	initBeanWrapper(bw);
	populateBean(bd.getBeanClass().getName(), bd, bw);
}
 
Example #25
Source File: CachedIntrospectionResults.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create CachedIntrospectionResults for the given bean class.
 * @param beanClass the bean class to analyze
 * @return the corresponding CachedIntrospectionResults
 * @throws BeansException in case of introspection failure
 */
@SuppressWarnings("unchecked")
static CachedIntrospectionResults forClass(Class<?> beanClass) throws BeansException {
	CachedIntrospectionResults results = strongClassCache.get(beanClass);
	if (results != null) {
		return results;
	}
	results = softClassCache.get(beanClass);
	if (results != null) {
		return results;
	}

	results = new CachedIntrospectionResults(beanClass);
	ConcurrentMap<Class<?>, CachedIntrospectionResults> classCacheToUse;

	if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) ||
			isClassLoaderAccepted(beanClass.getClassLoader())) {
		classCacheToUse = strongClassCache;
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
		}
		classCacheToUse = softClassCache;
	}

	CachedIntrospectionResults existing = classCacheToUse.putIfAbsent(beanClass, results);
	return (existing != null ? existing : results);
}
 
Example #26
Source File: AbstractFallbackTransactionAttributeSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result.
 * {@link #getTransactionAttribute} is effectively a caching decorator for this method.
 * <p>As of 4.1.8, this method can be overridden.
 * @since 4.1.8
 * @see #getTransactionAttribute
 */
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
	// Don't allow no-public methods as required.
	if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
		return null;
	}

	// Ignore CGLIB subclasses - introspect the actual user class.
	Class<?> userClass = ClassUtils.getUserClass(targetClass);
	// 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.
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

	// First try is the method in the target class.
	TransactionAttribute txAtt = findTransactionAttribute(specificMethod);
	if (txAtt != null) {
		return txAtt;
	}

	// Second try is the transaction attribute on the target class.
	txAtt = findTransactionAttribute(specificMethod.getDeclaringClass());
	if (txAtt != null) {
		return txAtt;
	}

	if (specificMethod != method) {
		// Fallback is to look at the original method.
		txAtt = findTransactionAttribute(method);
		if (txAtt != null) {
			return txAtt;
		}
		// Last fallback is the class of the original method.
		return findTransactionAttribute(method.getDeclaringClass());
	}
	return null;
}
 
Example #27
Source File: HsqlEmbeddedDatabaseConfigurer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Get the singleton {@link HsqlEmbeddedDatabaseConfigurer} instance.
 * @return the configurer instance
 * @throws ClassNotFoundException if HSQL is not on the classpath
 */
@SuppressWarnings("unchecked")
public static synchronized HsqlEmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException {
	if (instance == null) {
		instance = new HsqlEmbeddedDatabaseConfigurer( (Class<? extends Driver>)
				ClassUtils.forName("org.hsqldb.jdbcDriver", HsqlEmbeddedDatabaseConfigurer.class.getClassLoader()));
	}
	return instance;
}
 
Example #28
Source File: FileEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testUnqualifiedFileNameFound() throws Exception {
	PropertyEditor fileEditor = new FileEditor();
	String fileName = ClassUtils.classPackageAsResourcePath(getClass()) + "/" +
			ClassUtils.getShortName(getClass()) + ".class";
	fileEditor.setAsText(fileName);
	Object value = fileEditor.getValue();
	assertTrue(value instanceof File);
	File file = (File) value;
	assertTrue(file.exists());
	String absolutePath = file.getAbsolutePath().replace('\\', '/');
	assertTrue(absolutePath.endsWith(fileName));
}
 
Example #29
Source File: URLEditorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testClasspathURL() throws Exception {
	PropertyEditor urlEditor = new URLEditor();
	urlEditor.setAsText("classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) +
			"/" + ClassUtils.getShortName(getClass()) + ".class");
	Object value = urlEditor.getValue();
	assertTrue(value instanceof URL);
	URL url = (URL) value;
	assertEquals(url.toExternalForm(), urlEditor.getAsText());
	assertTrue(!url.getProtocol().startsWith("classpath"));
}
 
Example #30
Source File: AbstractApplicationEventMulticaster.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a Collection of ApplicationListeners matching the given
 * event type. Non-matching listeners get excluded early.
 * @param event the event to be propagated. Allows for excluding
 * non-matching listeners early, based on cached matching information.
 * @param eventType the event type
 * @return a Collection of ApplicationListeners
 * @see org.springframework.context.ApplicationListener
 */
protected Collection<ApplicationListener<?>> getApplicationListeners(
		ApplicationEvent event, ResolvableType eventType) {

	Object source = event.getSource();
	Class<?> sourceType = (source != null ? source.getClass() : null);
	ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);

	// Quick check for existing entry on ConcurrentHashMap...
	ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
	if (retriever != null) {
		return retriever.getApplicationListeners();
	}

	if (this.beanClassLoader == null ||
			(ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) &&
					(sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) {
		// Fully synchronized building and caching of a ListenerRetriever
		synchronized (this.retrievalMutex) {
			retriever = this.retrieverCache.get(cacheKey);
			if (retriever != null) {
				return retriever.getApplicationListeners();
			}
			retriever = new ListenerRetriever(true);
			Collection<ApplicationListener<?>> listeners =
					retrieveApplicationListeners(eventType, sourceType, retriever);
			this.retrieverCache.put(cacheKey, retriever);
			return listeners;
		}
	}
	else {
		// No ListenerRetriever caching -> no synchronization necessary
		return retrieveApplicationListeners(eventType, sourceType, null);
	}
}